Execution order of Enum in java

前端 未结 4 765
醉话见心
醉话见心 2021-01-12 10:14

I got a question about Enum.

I have an enum class looks like below

public enum FontStyle {
    NORMAL(\"This font has normal style.\"),
    BOLD(\"T         


        
4条回答
  •  走了就别回头了
    2021-01-12 10:41

    Enum instances are created during class linking (resolution), which is a stage that comes after class loading, just like static fields of a "normal" class.

    Class linking happens separately from class loading. So if you dynamically load the Enum class using a class loader, the constants will be instantiated only when you actually try to access one of the instances, for example, when using the method getEnumConstants() from Class.

    Here is a bit of code to test the above assertion:

    File1: TestEnum.java

    public enum TestEnum {
    
        CONST1, CONST2, CONST3;
    
        TestEnum() {
            System.out.println( "Initializing a constant" );
        }
    }
    

    File2: Test.java

    class Test
    {
        public static void main( String[] args ) {
    
            ClassLoader cl = ClassLoader.getSystemClassLoader();
    
            try {
                Class cls = cl.loadClass( "TestEnum" );
                System.out.println( "I have just loaded TestEnum" );
                Thread.sleep(3000);
                System.out.println( "About to access constants" );
                cls.getEnumConstants();
            } catch ( Exception e ) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }
    

    The output:

    I have just loaded TestEnum
    ... three seconds pause ...
    About to access constants
    Initializing a constant
    Initializing a constant
    Initializing a constant
    

    The distinction is important if, for any reason, you are not using the enum plainly (just by referring to one of its constants) but instead rely on dynamically loading it.

    Notes:

    • Using Class.forName() will both load and link the class, so the constants will be immediately instantiated.
    • It is enough to access one constant for the entire class to be linked, therefore all the constants will be instantiated at that time.

提交回复
热议问题