我有一个与此类似的类,并且findbugz提示“从实例方法写入静态字段”(initialize()killStaticfield())。我无法在ctor中设置静态字段。

  • 解决此问题的最佳方法是什么?
  • 将staticField放在AtomicReference中就足够了吗?
     public class Something
     {
      private static SomeClass staticField = null;
      private AnotherClass aClass;
      public Something()
      {
    
      }
    
      public void initialize()
      {
        //must be ctor'd in initialize
        aClass = new AnotherClass();
        staticField = new SomeClass( aClass );
      }
    
      public void killStaticField()
      {
       staticField = null;
      }
    
      public static void getStaticField()
      {
        return staticField;
      }
    }
    
  • 最佳答案

    尽可能保持与原始设计的距离...

    public class Something {
      private static volatile SomeClass staticField = null;
    
      public Something() {
      }
    
      public static SomeClass getStaticField() {
        if(Something.staticField == null)
          Something.staticField = new SomeClass();;
        return Something.staticField;
      }
    }
    

    通过类名引用您的静态变量,这将删除findbugz警告。
    将您的静态变量标记为volatile,这将使引用在多线程环境中更安全。

    更好的是:
    public class Something {
      private static final SomeClass staticField = new SomeClass();
    
      public Something() {
      }
    
      public static SomeClass getStaticField() {
        return Something.staticField;
      }
    }
    

    10-04 14:57