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静态成员变量),所以这种方式实际上又创建了一个实例。