为什么Java枚举常量初始化不完整? [英] Why the Java enum constants initialization is not complete?
问题描述
import java.awt.Color;
public class test {
/ **
* @param args
* /
public static void main(String [] args ){
System.out.println(MyEnum.CONSTANT1.get());
System.out.println(MyEnum.CONSTANT2.get());
}
private enum MyEnum {
CONSTANT1(staticMethod1()),
CONSTANT2(staticMethod2());
private static final颜色WHY_AM_I_NULL = new Color(255,255,255);
私人最终颜色;
私人MyEnum(颜色){
this.color = color;
}
public Color get(){
return color;
}
private static Color staticMethod1(){
return new Color(100,100,100);
}
private static Color staticMethod2(){
return WHY_AM_I_NULL;
}
}
}
结果当你运行它是:
java.awt.Color [r = 100,g = 100,b = 100]
null
问题是,为什么第二个是null?
Ammendment:
如果将WHY_AM_I_NULL放在枚举中的私有静态类中,那么它将被初始化。
问题是所有的静态字段(和枚举实例如此计数)都按其声明的顺序进行初始化(规范)。所以当 CONSTANT2
被实例化时,字段 WHY_AM_I_NULL
仍然没有初始化(因此 null
)。
由于您无法将该字段放在枚举实例之前,您必须找到一些其他方式来执行所需的操作(例如,将该字段放在枚举类之外)。如果你告诉我们,你真的想要完成什么,可以提出进一步的建议。
编辑如果你把嵌套类中的WHY_AM_I_NULL
,一旦类被首次访问(即在这种情况下执行 staticMethod2
)。
I stumbled upon a very weird bug and I can't explain why it happens. Imagine the following enum:
import java.awt.Color;
public class test {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(MyEnum.CONSTANT1.get());
System.out.println(MyEnum.CONSTANT2.get());
}
private enum MyEnum {
CONSTANT1(staticMethod1()),
CONSTANT2(staticMethod2());
private static final Color WHY_AM_I_NULL = new Color(255, 255, 255);
private final Color color;
private MyEnum(Color color) {
this.color = color;
}
public Color get() {
return color;
}
private static Color staticMethod1() {
return new Color(100, 100, 100);
}
private static Color staticMethod2() {
return WHY_AM_I_NULL;
}
}
}
The results when you run this are:
java.awt.Color[r=100,g=100,b=100]
null
The question is, why the second one is null?
Ammendment: If you put the WHY_AM_I_NULL in a private static class inside the enum, then it is initialized first.
The problem is that all static fields (and enum instances count as such) are initialized in their declared order (specification). So when CONSTANT2
is instantiated, the field WHY_AM_I_NULL
is still not initialized (and therefore null
).
As you can't put the field before the enum instances, you have to find some other way of doing what you want (e.g., putting the field outside the enum class). If you tell us, what you really want to accomplish, one could make further suggestions.
Edit: If you put WHY_AM_I_NULL
in a nested class, the fields of this class will be initialized as soon as the class is first accessed (i.e., in this case during the execution of staticMethod2
).
这篇关于为什么Java枚举常量初始化不完整?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!