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