我有一个关于Enum的问题。
我有一个枚举类如下
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对象。
枚举看起来像“静态最终”对象,因为它的值永远不会改变。因此,为此目的,仅在编译时进行初始化是有效的。
但是它在顶部调用了自己的构造函数,因此我怀疑它是否会在我们调用它时生成,例如在switch语句中。
是的,枚举是静态常量,但不是编译时间常量。就像其他任何类一样,在第一次需要枚举时会被加载。如果稍微更改其构造函数,就可以轻松观察它
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");
如果尚未加载,则会导致其加载。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句