如何获取sun.misc.Unsafe的实例?

问题描述 投票:0回答:3

如何获取不安全类的实例?

我总是遇到安全异常。我列出了 OpenJDK 6 实现的代码。我想摆弄

sun.misc.Unsafe
提供给我的功能,但我总是得到
SecurityException("Unsafe")

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

(请不要试图告诉我使用此类是多么不安全。)

java unsafe
3个回答
6
投票

baeldung.com,我们可以使用反射获取实例:

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

2
投票

如果你使用 Spring,你可以使用它的类

UnsafeUtils

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
投票

还有另一种方法可以找到:

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

在不安全的源代码中,你可以找到:

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

您可以使用 Xbootclasspath 将您的类或 jar 添加到引导类路径,如下所示:

java -Xbootclasspath:/usr/jdk1.7.0/jre/lib/rt.jar:. com.mishadoff.magic.UnsafeClient
© www.soinside.com 2019 - 2024. All rights reserved.