Unsafe类
一、Unsafe类仅能被BootstrapClassLoader加载的类实例化,用户建的类默认都是ApplicationClassLoader加载的,实例化Unsafe时会报错。可以用反射实例化(方式一)。补充:加启动参数指定当前类由BootstrapClassLoader加载(方式二) private Unsafe() {//构造方法私有化 同单例模式 防止new } @CallerSensitive public static Unsafe getUnsafe() { Class var0 = Reflection.getCallerClass(); if (!VM.isSystemDomainLoader(var0.getClassLoader())) {//判断是否BootstrapClassLoader加载的类执行实例化的 throw new SecurityException("Unsafe"); } else { return theUnsafe; } } 二、反射实现实例化 public class UnsafeTest2 { static final Unsafe unsafe; static final long stateOffset; private volatile long state = 0; static { try { Field field =