Why sun.misc.Unsafe # getUnsafe () cannot be found using Java reflection?
Once I successfully load the class sun.misc.Unsafe
by reflection, I cannot find the method getUnsafe
as a declared method using Java reflection. What for? I have not SecurityManager
.
This is my code that always produces NoSuchMethodException
:
Class<?> c = Class.forName("sun.misc.Unsafe", false, getClass().getClassLoader());
Assert.assertNotNull(c.getDeclaredMethod("getUnsafe"));
source to share
If you are using Java 8, you are not allowed to see this method and other internal methods. See The sun.reflect.Reflection Class.
Under the static block of this class, you can see
Reflection.registerMethodsToFilter(Unsafe.class, new String[]{"getUnsafe"});
This adds a filter for this method so it doesn't appear through reflection.
In Java 9, the goal is to make it even harder to access such inner classes.
At the moment you can get the field directly from Java 9 build 63.
Class<?> c = Class.forName("sun.misc.Unsafe", false, A.class.getClassLoader());
Field theUnsafe = c.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe u = (Unsafe) theUnsafe.get(null);
System.out.println("u= " + u);
Note: you can expect this to not work in future versions.
source to share