如何使用方法句柄调用私有(private)方法?
据我所知,只有两种可公开访问的 Lookup
实例:
MethodHandles.lookup()
MethodHandles.publicLookup()
并且都不允许不受限制的私有(private)访问。
有一个非公开的 Lookup.IMPL_LOOKUP
可以满足我的要求。是否有一些公共(public)方式来获取它(假设 SecurityManager 允许)?
最佳答案
事实证明,使用 Lookup#unreflect(Method) 并暂时使方法可访问是可能的(除非在程序初始化期间完成,否则可能会引入小的安全问题)。
这里修改了 Thorben 的回答中的 main 方法:
public static void main(String[] args) {
Lookup lookup = MethodHandles.lookup();
NestedTestClass ntc = new Program().new NestedTestClass();
try {
// Grab method using normal reflection and make it accessible
Method pm = NestedTestClass.class.getDeclaredMethod("gimmeTheAnswer");
pm.setAccessible(true);
// Now convert reflected method into method handle
MethodHandle pmh = lookup.unreflect(pm);
System.out.println("reflection:" + pm.invoke(ntc));
// We can now revoke access to original method
pm.setAccessible(false);
// And yet the method handle still works!
System.out.println("handle:" + pmh.invoke(ntc));
// While reflection is now denied again (throws exception)
System.out.println("reflection:" + pm.invoke(ntc));
} catch (Throwable e) {
e.printStackTrace();
}
}
关于java - 使用 java.lang.invoke.MethodHandle 调用私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19135218/