我将单例对象的引用分配给 null。
但它仍然是单例类的调用方法。
这是我的代码
class Singleton {
private static Singleton singleton = new Singleton();
/*
* A private Constructor prevents any other class from instantiating.
*/
private Singleton() {
}
/* Static 'instance' method */
public static Singleton getInstance() {
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod() {
System.out.println("demoMethod for singleton");
}
}
public class SingletonDemo {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance();
tmp.demoMethod();
tmp = null;
tmp.demoMethod();
}
}
最佳答案
这是因为 demoMethod()
是 static
(因此,它不是 Singleton
实例状态的一部分) >,而是类定义的一部分)
发生的情况是,您不是在引用变量 tmp
,而是在类 Singleton
via tmp
变量。这应该由 IDE 作为警告发出(通常,Eclipse 和 IntelliJ 会这样做)。
如果删除 static
关键字,您将得到预期的 NullPointerException
。
关于java - 单例的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30333783/