关于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 加不加都不会报错
这是为什么?

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

这是什么问题呢

img

img

静态代码块中的异常原则上必须处理,不应该也不能再往上抛
原因:在类加载器,加载该类时,首先执行的就是static{}块中的代码,
如果static{}块中的异常没有处理,异常就会导致该类加载失败,
也就是说“该类夭折,不存在”,显然与其相关的操作肯定就不能执行
如果你“不得不”向外抛只能这样写
抛出 运行式异常 (这样写,实质上也应该算是处理了异常)
throw new RuntimeException(e);