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

3

20

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.)

Ziska answered 22/10, 2012 at 1:18 Comment(1)
It's worth noting that this is intentionally undocumented, not only because it's unsafe, not a formal part of the Java API, and not formally supported, but also because you're sort of intended to "build your own lightsaber": if you can't figure out how to get an instance of Unsafe on your own, you probably don't understand the JVM well enough to use the Unsafe without causing problems.Pseudonymous
M
6

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

   Field f =Unsafe.class.getDeclaredField("theUnsafe");
   f.setAccessible(true);
   unsafe = (Unsafe) f.get(null);
Mood answered 3/1, 2019 at 21:32 Comment(0)
G
2

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);
        }
    }
}
Goddamn answered 5/1, 2020 at 23:46 Comment(0)
G
0

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
Gabble answered 26/10, 2020 at 6:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.