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

前端 未结 3 1472
萌比男神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);
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-19 01:17

    There is another way of doing it you can find in:

    http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/

    in unsafe source code, you can find:

    @CallerSensitive
    public static Unsafe getUnsafe() {
        Class<?> caller = Reflection.getCallerClass();
        if (!VM.isSystemDomainLoader(caller.getClassLoader()))
            throw new SecurityException("Unsafe");
        return theUnsafe;
    }
    

    you can add your class or jar to bootstrap classpath by using Xbootclasspath, as below:

    java -Xbootclasspath:/usr/jdk1.7.0/jre/lib/rt.jar:. com.mishadoff.magic.UnsafeClient
    
    0 讨论(0)
  • 2021-02-19 01:28

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

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

    Edit

    The following is quoted from the description of the project where this code belongs to.

    "The implementation of all these examples and code snippets can be found over on GitHub – this is a Maven project, so it should be easy to import and run as it is."

    0 讨论(0)
提交回复
热议问题