Java中Enum的执行顺序 [英] Execution order of Enum in java

查看:113
本文介绍了Java中Enum的执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于枚举的问题。

I got a question about Enum.

我有一个如下所示的枚举类

I have an enum class looks like 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;
    }
}

我想知道何时创建此Enum对象。

I wonder when this Enum object is created.

枚举看起来像静态最终对象,因为它的值永远不会改变。
因此,仅在编译时进行初始化非常有效。

Enum looks like 'static final' Object since its value will never changed. So in that purpose, it is efficient to initialize in compile time only.

但是它在顶部调用了它自己的构造函数,因此我怀疑它在我们调用它时是否会生成,例如在switch语句中。

But it calls its own constructor in top, so I doubt that it could generate whenever we call it, for example, in switch statement.

推荐答案

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

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.

这篇关于Java中Enum的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆