我使用单例类SingletonA作为我的资源,我有一个使用资源的服务ServiceS。
--log-level=debug
- >在ServicesS类中,sa值为 null - > sa.printResources()导致 NPE
但是,因为我将另外一个 sa = SingletonA.getInstance(); 添加到ServiceS.printResources()中,如下所示:
public class SingletonA {
private static SingletonA ourInstance = new SingletonA();
public static SingletonA getInstance() { return ourInstance; }
private SingletonA () {}
String resources;
synchronized public void importSomething() {
resources = "I have some value now";
}
}
public class ServiceS extends Handler {
private static ServiceS ourInstance = new ServiceS();
public static ServiceS getInstance() { return ourInstance; }
private ServiceS () {}
SingletonA sa = SingletonA.getInstance();
public void printResources() {
println(sa.resources);
}
}
public class MyActivity extends Activity {
SingletonA sa = SingletonA.getInstance();
@override
protected void onCreateBundle savedInstanceState) {
super.onCreate(savedInstanceState);
sa.importSomthing();
ServiceS.printResources();
}
}
- > 有效:sa!= null和resources ="我现在有一些价值"。 有人可以解释为什么ServiceS中的sa仍然为空?谢谢,
答案 0 :(得分:0)
作为Buddy的评论:
这是由于静态初始化顺序。静态ServiceS.ourService在SingletonA.ourInstance。
之前初始化See here for more information on static initialization order。但是,简单的解决方案是在必要时调用SingletonA.getInstance()(与成员变量中的缓存相比)。或者懒惰地初始化getInstance中的ServiceS.ourInstance