Enum execution order in java

I have a question about Enum.

My enum class looks below

public enum FontStyle {
    NORMAL("This font has normal style."),
    BOLD("This font has bold style."),
    ITALIC("This font has italic style."),
    UNDERLINE("This font has underline style.");

    private String description;

    FontStyle(String description) {
        this.description = description;
    }
    public String getDescription() {
        return this.description;
    }
}

I wonder when this Enum object was created.

Enum looks like a static final object because its value will never be changed. Therefore, for this purpose, it is only efficient to initialize at compile time.

But it calls its own constructor from above, so I doubt that it can generate whenever we call it, for example, in a switch statement.

+4
source share
3 answers

, , . , . ,

FontStyle(String description) {
    System.out.println("creating instace of "+this);// add this
    this.description = description;
}

,

class Main {
    public static void main(String[] Args) throws Exception {
        System.out.println("before enum");
        FontStyle style1 = FontStyle.BOLD;
        FontStyle style2 = FontStyle.ITALIC;
    }
}

main,

before enum
creating instace of NORMAL
creating instace of BOLD
creating instace of ITALIC
creating instace of UNDERLINE

, enum ( ) , enum .

Class.forName("full.packag.name.of.FontStyle");

, .

+3

, Enum.

, , (==). (de) .

0

Enum (), , , "normal".

. , Enum , , , , getEnumConstants() Class.

:

1: TestEnum.java

public enum TestEnum {

    CONST1, CONST2, CONST3;

    TestEnum() {
        System.out.println( "Initializing a constant" );
    }
}

2: 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);
        }
    }
}

:

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

, - ( ), .

:

  • Class.forName() , .
  • , .
0

All Articles