How do I get the instance of sun.misc.Unsafe?

前端 未结 3 1476
萌比男神i
萌比男神i 2021-02-19 00:32

How do I get the instance of the unsafe class?

I always get the security exception. I listed the code of the OpenJDK 6 implementation. I would like to mess around with

3条回答
  •  名媛妹妹
    2021-02-19 01:17

    If you use Spring, you can use its class called UnsafeUtils

    at org.springframework.objenesis.instantiator.util.UnsafeUtils

    public final class UnsafeUtils {
        private static final Unsafe unsafe;
    
        private UnsafeUtils() {
        }
    
        public static Unsafe getUnsafe() {
            return unsafe;
        }
    
        static {
            Field f;
            try {
                f = Unsafe.class.getDeclaredField("theUnsafe");
            } catch (NoSuchFieldException var3) {
                throw new ObjenesisException(var3);
            }
    
            f.setAccessible(true);
    
            try {
                unsafe = (Unsafe)f.get((Object)null);
            } catch (IllegalAccessException var2) {
                throw new ObjenesisException(var2);
            }
        }
    }
    

提交回复
热议问题