[英]Static non-final variable used during initialization
See this incomplete code fragment: 请参阅以下不完整的代码片段:
public class Singleton implements Serializable {
private static class SingletonHolder {
private static final Singleton SINGLETON_INSTANCE;
static {
Singleton tmp = singletonTMP;
if (tmp != null) {
SINGLETON_INSTANCE = tmp;
} else {
// etc.
}
}
}
private static volatile Singleton singletonTMP;
// etc.
}
I get a strange warning in NetBeans at line Singleton tmp = singletonTMP;
我在NetBeans中的
Singleton tmp = singletonTMP;
处收到一个奇怪的警告Singleton tmp = singletonTMP;
: "Usage of static non-final variable used during initialization". :“初始化期间使用静态非最终变量”。
So, yes. 所以,是的。 This is true, of course, but why would this be a problem?
当然,这是对的,但是为什么会出现问题呢?
The problem is that the variable : 问题是变量:
private static final Singleton SINGLETON_INSTANCE;
might not have been initialized in that static block of yours, you can inititalize it to null(say) in the else clause inside that static block, ie: 可能尚未在您的该静态块中初始化,您可以在该静态块内的else子句中将其初始化为null(例如)。
static
{
Singleton tmp = singletonTMP;
if (tmp != null)
{
SINGLETON_INSTANCE = tmp;
} else
{
**SINGLETON_INSTANCE = null;**
}
}
After reading a bit about security I think my previous comment was correct. 在阅读了一些有关安全性的知识之后,我认为我先前的评论是正确的。
I think it is a security issue, an attacker could replace your static field with a new object. 我认为这是一个安全问题,攻击者可以用新对象替换您的静态字段。 This happens when the attribute is also defined as public.
当属性也定义为公共时,就会发生这种情况。 I assume netbeans considers it a risk and displays the warning even if you declared it private.
我认为netbeans认为这是一种风险,即使您将其声明为私有也将显示警告。
More details here: https://www.securecoding.cert.org/confluence/display/java/OBJ10-J.+Do+not+use+public+static+nonfinal+variables 此处有更多详细信息: https : //www.securecoding.cert.org/confluence/display/java/OBJ10-J.+Do+not+use+public+static+nonfinal+variables
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.