我的代码目前遇到“可能对构造函数中的非最终静态字段进行不安全分配”(PMD 中的 AssignmentToNonFinalStatic)。
该类被编写为单例类,受此警告影响的属性如下所示
私有(private)静态字符串 myProperty;
并由这个构造填充:
public SystemPropertyUtils() throws ConfigException {
someMethodThrowingConfigException();
myProperty = "someValue" + this.someOtherValueFromAThreadSafeString;
}
是否有详细的方法来否定此警告?
最佳答案
不要在构造函数中设置静态字段。在这种情况下,将字段设为非静态。
否则,我不得不怀疑您不需要构造函数。相反,您可以在静态初始化程序 block 或静态方法中初始化静态字段。
关于java - 如何避免 "Possible unsafe assignment to a non-final static field in a constructor"(AssignmentToNonFinalStatic),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9671857/