Execution order of Enum in java

前端 未结 4 844
醉话见心
醉话见心 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:57

    Yes, enums are static constants but are not compile time constants. Just like any other classes enum is loaded when first time needed. You can observe it easily if you change its constructor a little

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

    and use simple test code like

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

    If you will run main method you will see output

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

    which shows that enum class was loaded (and its static fields have been initialized) right when we wanted to use enum first time.

    You can also use

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

    to cause its load if it wasn't loaded yet.

提交回复
热议问题