weixin_44089714 2021-07-13 14:32 采纳率: 16.7%
浏览 115

关于final关键字的使用问题

class UnsafeAccessor {

    private static Unsafe unsafe;

    static {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
              unsafe = (Unsafe) theUnsafe.get(null);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static Unsafe getUnsafe() {
        return unsafe;
    }
}
class MyAtomicInteger {

    private static final Unsafe UNSAFE;

    static {
        UNSAFE = UnsafeAccessor.getUnsafe();
    }
}

两个类 MyAtomicInteger 中使用了 UnsafeAccessor 的方法
现在我的问题是 UnsafeAccessor 中的 成员变量 unsafe 为什么不能用final修饰,
如果我加了final修饰,会先报错说 ‘Variable 'unsafe' might not have been initialized’
如果给他初始化了, ‘unsafe = (Unsafe) theUnsafe.get(null);’ 这行代码又会报错 ‘Cannot assign a value to final variable 'unsafe'’

但是 MyAtomicInteger 这类的成员变量 UNSAFE 的 final 加不加都不会报错
这是为什么?

  • 写回答

4条回答 默认 最新

  • 八云黧 2021-07-13 14:37
    关注

    加了final修饰,会先报错说 ‘Variable 'unsafe' might not have been initialized’是因为这是一句警告(不是错误!),一个变量没有初始化IDE都会给出这种警告,因为使用未初始化的变量很容易引起空指针异常。
    给他初始化了, ‘unsafe = (Unsafe) theUnsafe.get(null);’ 这行代码又会报错 ‘Cannot assign a value to final variable 'unsafe'’是因为这是一个错误,final的变量一旦赋值(就是初始化)就不能再更改,这是报错。
    所以解决方案应该是配置ide让这个变量不在显示初始化警告

    评论

报告相同问题?

问题事件

  • 创建了问题 7月13日

悬赏问题

  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红
  • ¥15 想问问富文本拿到的html怎么转成docx的
  • ¥15 我看了您的文章,遇到了个问题。
  • ¥15 GitHubssh虚拟机连接不上
  • ¥15 装完kali之后下载Google输入法 重启电脑后出现以下状况 且退不出去 桌面消失 反复重启没用