繁体   English   中英

null引用的Singleton类对象

[英]Singleton class object referenced by null

我有一个单例类,并且在我的项目中的许多地方都引用了它的实例。 现在,我看到一个这样的地方,其中为单例实例分配了NULL引用。

问题是:1.它是否会指向其余地方的空引用? 2.如果是这种情况,如何避免这种情况?

这是代码片段。

public enum Test {
   INSTANCE;
       public void fun(){
       System.out.println("hello");
   }  
}

public class Main {

   public static void main(String[] args) {
       Test test = Test.INSTANCE;
       test.fun();
       test = null;
       test.fun();
   }
}

不,只有main的局部变量test设置为null。

Test.INSTANCE仍指向单个全局实例。 由于它是一个枚举,因此您甚至不能强制Test.INSTANCE为null。


但是,请考虑以下(反)示例,该示例说明了如何将静态引用重置为null:

public class Test {
   public static Test INSTANCE = new Test();

   public void fun(){
       System.out.println("hello");
   }  
}

public class Main {
   public static void main(String[] args) {
       Test test = Test.INSTANCE;
       test.fun();
       test = null; // test is null, but Test.INSTANCE still points to the global instance
       Test.INSTANCE = null; // now even Test.INSTANCE is null
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM