且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java中Enum的执行顺序

更新时间:2023-11-30 10:48:52

是的,枚举是静态常量,但不是编译时间常量。就像其他任何类一样,在第一次需要枚举时会被加载。

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;
    }
}

如果要运行 main 方法,您将看到输出

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.

您也可以使用

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

如果尚未加载将导致其加载。

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