Java – what is the best way to modify “write static fields” from the instance method “findbugs” warning?
•
Java
I have a similar class, findbugz complains about "writing static fields from instance methods (initialize () and killstaticfield())." I cannot set static fields in ctor
>What is the best solution to this problem? Will you put staticfield in 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;
}
}
Solution
As close to your original design as possible
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;
}
}
Refer to your static variable by class name, which will remove the findbugz warning Marking static variables volatile makes references safer in a multiparameter environment
Better yet:
public class Something {
private static final SomeClass staticField = new SomeClass();
public Something() {
}
public static void getStaticField() {
return Something.staticField;
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
