[英]How to call methods within Java Singleton enum constructor?
My sample enum Singleton class is: 我的示例枚举Singleton类是:
public class Test{
public enum MyClass{
INSTANCE;
private static String name = "Hello";
MyClass() {
test();
}
private static void test(){
name = name + "World";
System.out.println(name);
}
}
public static void main(String a[]){
MyClass m1 = MyClass.INSTANCE;
}
}
Obtained output : nullWorld 获得的输出:nullWorld
Expected output : HelloWorld 预期输出:HelloWorld
In main(), if 在main()中,if
MyClass m1 = MyClass.INSTANCE;
is replaced by 被替换为
MyClass.INSTANCE.test();
then, the output is HelloWorld, as expected. 然后,输出是HelloWorld,正如预期的那样。
This shows that static fields are not initialized until the constructor has completed execution. 这表明在构造函数完成执行之前,不会初始化静态字段。
Question : How to achieve this functionality of calling a method within constructor that accesses static fields? 问题:如何实现在访问静态字段的构造函数中调用方法的这种功能?
This is because INSTANCE
is declared before name
, so it is created and initalized before name
is initialized. 这是因为在name
之前声明了INSTANCE
,因此在初始化name
之前创建它并初始化。
This works: 这有效:
public enum MyClass{
INSTANCE;
private static final String name = "Hello";
MyClass() {
test();
}
private static void test(){
String name1 = name + "World";
System.out.println(name1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.