我有一个类似于此类,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 void 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 void getStaticField() { return Something.staticField; } }