Search code examples
javaunsafe

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


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 the function sun.misc.Unsafe offers to me, but I always end up getting the SecurityException("Unsafe").

public static Unsafe getUnsafe() {
    Class cc = sun.reflect.Reflection.getCallerClass(2);
    if (cc.getClassLoader() != null)
        throw new SecurityException("Unsafe");
    return theUnsafe;
}

(Please don't try to tell me how unsafe it is to use this class.)


Solution

  • From baeldung.com, we can get the instance using reflection:

       Field f =Unsafe.class.getDeclaredField("theUnsafe");
       f.setAccessible(true);
       unsafe = (Unsafe) f.get(null);