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

查看:87
本文介绍了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中枚举的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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