Java Unsafe-如何得到Unsafe

Unsafe(sun.misc.Unsafe)是jdk中自带的一个类,因为是在sun.misc包下,所以一般也不建议直接使用,同时Unsafe提供了一组底层(low-level)、unsafe的操作。Unsafe类注释中也有这样一段描述:

虽然该类及所有方法都是公开的,但使用该类是有限的,因为只有受信任的代码才能获得它的实例。

 

如何得到Unsafe

@CallerSensitive

public static Unsafe getUnsafe() {

Class cc = Reflection.getCallerClass();

if (cc.getClassLoader() != null)

        throw new SecurityException("Unsafe");

    return theUnsafe;

}

注意这个方法上有个@CallerSensitive注解。

但如果使用这个方法来尝试得到Unsafe的话,恐怕不能直接如偿所愿了。该方法正常调用将返回错误。

@Test

publicvoid getUnsafe1() throws Throwable {

Unsafe unsafe = getUnsafe();

Assert.assertNotNull(unsafe);

}

错误信息如下:

java.lang.SecurityException: Unsafe

    at sun.misc.Unsafe.getUnsafe(Unsafe.java:68)

    at com.java.UnsafeTest.getUnsafe0(UnsafeTest.java:25)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

    at java.lang.reflect.Method.invoke(Method.java:597)

    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)

    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)

    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)

    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)

    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)

    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)

    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)

    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)

    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)

    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)

    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)

    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)

    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)

    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)

    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)

    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)

    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)

    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)

    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

 

原因在与Unsafe类中getUnsafe方法被标注为@CallerSensitive,其中有如下一条代码:

Class cc = Reflection.getCallerClass();

它调用了Reflection类的getCallerClass()方法,Reflection类(sun.reflect.Reflection)在jdk\src\share\classes\sun\reflect目录下。该方法是个native方法:

@CallerSensitive

public static native Class getCallerClass();

对应的实现Reflection.c在jdk\src\share\native\sun\reflect目录下。该方法实现:

JNIEXPORT jclass JNICALL Java_sun_reflect_Reflection_getCallerClass

(JNIEnv *env, jclass unused)

{

    // Until there is hotspot @CallerSensitive support,

    // depth must always be 2 to get the immediate caller

    return JVM_GetCallerClass(env, 2);

}

这个方法直接调用了JVM_GetCallerClass方法,这里第二个参数表示深度(depth), 固定传值2表示得到直接调用者, 该方法实现jvm.cpp在hotspot\src\share\vm\prims目录下。该方法实现:

JVM_ENTRY(jclass, JVM_GetCallerClass(JNIEnv* env, int depth))

  JVMWrapper("JVM_GetCallerClass");

  klassOop k = thread->security_get_caller_class(depth);

  return (k == NULL) ? NULL : (jclass) JNIHandles::make_local(env, Klass::cast(k)->java_mirror());

JVM_END

 

Class classLoader:

Class类的classLoader字段,反射访问这个字段是被过滤掉的,所以通过reflection(反射)方式无法访问到这个字段。

1、Initialized in JVM not by private constructor

2、This field is filtered from reflection access, i.e. getDeclaredField will throw NoSuchFieldException

 

@org.junit.Test
public void getClassLoader() {
    Class klass = this.getClass();
    ClassLoader classLoader = klass.getClassLoader();
    Assert.assertNotNull(classLoader);

    Object field = null;
    try {
        field = field(klass, "classLoader");
        Assert.fail("fail");
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    Assert.assertNull(field);
}

 

 

可以通过反射的方式来访问Unsafe类中的theUnsafe静态成员变量,该theUnsafe静态成员变量在Unsafe第一次使用时就已经初始化。

private Unsafe getUnsafe() throws Throwable {

Class<?> unsafeClass = Unsafe.class;

for (Field f : unsafeClass.getDeclaredFields()) {

if ("theUnsafe".equals(f.getName())) {

f.setAccessible(true);

return (Unsafe) f.get(null);

}

}

thrownew IllegalAccessException("no declared field: theUnsafe");

}

 

@Test

publicvoid getUnsafe1() throws Throwable {

Unsafe unsafe = getUnsafe();

Assert.assertNotNull(unsafe);

}

另一种方式也是通过反射的方式调用私有构造方法

@Test

publicvoid getUnsafe2() throws Throwable {

Constructor<Unsafe> constructor = Unsafe.class.getDeclaredConstructor(new Class<?>[0]);

constructor.setAccessible(true);

Unsafe unsafe = constructor.newInstance(new Object[0]);

Assert.assertNotNull(unsafe);

}

由于在Unsafe第一次使用时就已经初始化创建了一个实例(Unsafe类中的theUnsafe静态成员变量),所以这种方式实际上又创建了一个实例。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值