正在阅读名为Emergent Design的书和关于单身人士的主题......
public class MyApp {
private class SingletonHolder {
public Object singleton;
static {
singleton = new Object();
}
}
}
然后eclipse一直抱怨静态{}
正在阅读Java,类应该能够拥有多个静态初始化程序。那么我怎样才能完成上述工作呢?
/tmp/jc_4873/MyApp.java:5: non-static variable singleton cannot be referenced from a static context
singleton = new Object();
^
/tmp/jc_4873/MyApp.java:4: inner classes cannot have static declarations
static {
^
2 errors
public class MyApp {
private class SingletonHolder {
public static Object singleton;
static {
singleton = new Object();
}
}
}
/tmp/jc_8488/MyApp.java:3: inner classes cannot have static declarations
public static Object singleton;
^
/tmp/jc_8488/MyApp.java:4: inner classes cannot have static declarations
static {
^
2 errors
public class MyApp {
private static class SingletonHolder {
public static Object singleton;
static {
singleton = new Object();
}
}
}
答案 0 :(得分:6)
对于要在静态上下文中合法引用的字段,该字段必须是上下文的本地字段,或者在类中声明为静态字段。如果您想引用singleton
,则需要声明static
。
答案 1 :(得分:2)
你需要把private static Object singleton;
静态块不能修改非静态变量。