问题描述
我有一个看起来与此类似的类,并且findbugz抱怨'从实例方法写入静态字段'( initialize()
,以及 killStaticfield()
)。我无法在ctor中设置静态字段。
I have a class that looks similar to this, and findbugz is complaining about the 'write to the static field from the instance method' (initialize()
, and killStaticfield()
). I can't set the static field in the ctor.
- 此问题的最佳解决方案是什么?
-
将staticField置于AtomicReference中是否足够?
- What is the best fix for this issue?
Would putting staticField in an AtomicReference suffice?
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;
}
}
推荐答案
尽可能接近原始设计...
Staying as close as possible to your original design...
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,这将使参考在多线程环境中更安全。
Refer to your static variable via the class name, that will remove the findbugz warning.Mark your static variable as volatile, which will make the reference safer in a multithreaded environment.
更好的是:
public class Something {
private static final SomeClass staticField = new SomeClass();
public Something() {
}
public static SomeClass getStaticField() {
return Something.staticField;
}
}
这篇关于什么是解决这个'从实例方法写入静态字段'的最佳方法'findbugs警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!