Java 独生子女的奇怪行为

Java 独生子女的奇怪行为,java,singleton,Java,Singleton,我将singleton对象的引用赋值为null 但它仍然在调用Singleton类的方法 这是我的密码 class Singleton { private static Singleton singleton = new Singleton(); /* * A private Constructor prevents any other class from instantiating. */ private Singleton() { } /* Static 'instance' m

我将singleton对象的引用赋值为null

但它仍然在调用Singleton类的方法

这是我的密码

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
,这是一种静态方法-因此您的代码如下:

tmp.demoMethod();
实际上是为了:

Singleton.demoMethod();
这显然不取决于
tmp
的值

这与作为单体方面完全无关:

public class Test {
    public static void main(String[] args) {
        String x = null;
        System.out.println(x.valueOf(10)); // Calls String.valueOf(10)
    }
}

请注意,Eclipse在这些方法调用下放置了黄色的曲线-我强烈怀疑如果您查看警告,您会看到它告诉您不要像这样调用静态方法。遵循建议,您不会出现奇怪的行为…

这是因为
demoMethod()
静态的(因此,它不是
单例的实例状态的一部分,而是类定义的一部分)

发生的情况是,您不是指变量
tmp
,而是指通过
tmp
变量的类
Singleton
。IDE应该发出警告(通常,Eclipse和IntelliJ会这样做)


如果删除
static
关键字,您将获得预期的
NullPointerException
方法
demoMethod
是静态的。它不绑定到任何
Singleton
类的实例。您应该将其更改为实例方法:

protected void demoMethod() {
    System.out.println("demoMethod for singleton");
}   

这是因为
demoMethod()
static
。如果您获得了使用类名访问类静态字段的习惯:
Singleton.demoMethod()
,那么您将不会遇到此类问题。他们不应该允许在实例上调用静态方法。还有一个语义歧义——静态方法调用在哪个类上?实例的静态类或运行时类。这种行为可能会违反程序员的直觉。