【问题标题】:Static non-final variable used during initialization初始化期间使用的静态非最终变量
【发布时间】:2014-11-20 09:38:56
【问题描述】:

查看这个不完整的代码片段:

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.

}

我在 NetBeans 中的 Singleton tmp = singletonTMP; 行收到一个奇怪的警告:“Usage of static non-final variable used during initialization”。

所以,是的。这当然是对的,但为什么会出现这样的问题呢?

【问题讨论】:

  • 我认为这是一个安全问题,攻击者可以用新对象替换您的静态字段。当属性也被定义为公共时,就会发生这种情况。我假设 netbeans 认为这是一种风险并显示警告,即使您将其声明为私有

标签: java netbeans static final


【解决方案1】:

问题在于变量:

private static final Singleton SINGLETON_INSTANCE;

可能尚未在您的静态块中初始化,您可以在该静态块内的 else 子句中将其初始化为 null(say),即:

    static 
    {
        Singleton tmp = singletonTMP;
        if (tmp != null) 
        {
            SINGLETON_INSTANCE = tmp;
        } else
        {
            **SINGLETON_INSTANCE = null;**
        }
    }

【讨论】:

  • 嗯。不,抱歉我的代码不完整。但是我已经在 else 分支中初始化了SINGLETON_INSTANCE。这一定不是问题。
【解决方案2】:

在阅读了一些关于安全性的内容后,我认为我之前的评论是正确的。

我认为这是一个安全问题,攻击者可以用新对象替换您的静态字段。当属性也被定义为公共时,就会发生这种情况。我假设 netbeans 认为这是一种风险并显示警告,即使您将其声明为私有。

更多细节在这里: https://www.securecoding.cert.org/confluence/display/java/OBJ10-J.+Do+not+use+public+static+nonfinal+variables

【讨论】:

  • private 本身不保护字段:它仍然可以通过反射访问(IDE 调试器所做的......)
猜你喜欢
  • 2013-09-30
  • 1970-01-01
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多