13

如何使用方法句柄调用私有方法?

据我所知,只有两种可公开访问的Lookup实例:

  • MethodHandles.lookup()
  • MethodHandles.publicLookup()

并且两者都不允许不受限制的私人访问。

有非公众Lookup.IMPL_LOOKUP做我想做的事。是否有一些公开的方式来获取它(假设 SecurityManager 允许它)?

4

3 回答 3

14

事实证明,可以使用 Lookup#unreflect(Method) 并暂时使方法可访问(除非在程序初始化期间完成,否则可能会引入小的安全问题)。

这是 Thorben 的回答修改后的主要方法:

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();
    }

}
于 2014-06-17T17:17:20.807 回答
3

I don't know, if this is what you really want. Perhaps you could give some more information about what you want to achieve with it. But if you want to access Lookup.IMPL_LOOKUP, you can do it like in this code sample:

public class Main {

public static void main(String[] args) {

    Lookup myLookup = MethodHandles.lookup(); // the Lookup which should be trusted
    NestedTestClass ntc = new Main().new NestedTestClass(); // test class instance

    try {
        Field impl_lookup = Lookup.class.getDeclaredField("IMPL_LOOKUP"); // get the required field via reflections
        impl_lookup.setAccessible(true); // set it accessible
        Lookup lutrusted = (Lookup) impl_lookup.get(myLookup); // get the value of IMPL_LOOKUP from the Lookup instance and save it in a new Lookup object

        // test the trusted Lookup
        MethodHandle pmh = lutrusted.findVirtual(NestedTestClass.class, "gimmeTheAnswer", MethodType.methodType(int.class));
        System.out.println(pmh.invoke(ntc));

    } catch (Throwable e) {
        e.printStackTrace();
    }

}

// nested class with private method for testing
class NestedTestClass{

    @SuppressWarnings("unused")
    private int gimmeTheAnswer(){

        return 42;
    }
}

}

It works with JDK 7, but could break in JDK 8. And be cautious! My antivirus gave an alarm when I executed it. I think there isn't a public or clean way to do it.

I had a similar issue and finally found a solution: Access non-public (java-native) classes from JDK (7).

于 2013-10-03T11:31:05.513 回答
-2

这是一个类似的解决方案,其中包含私有函数中的参数(我只是碰巧有以前项目中的代码):

类名:InspectionTree.java

函数签名:私有 String getSamePackagePathAndName(String className, String classPath)

String firstName = "John";
String lastName = "Smith";

//call the class's constructor to set up the instance, before calling the private function
InspectionTree inspectionTree = new InspectionTree(firstName, lastName);

String privateMethodName ="getSamePackagePathAndName";        
Class[] privateMethodArgClasses = new Class[] { String.class, String.class };

Method method = 
         inspectionTree.getClass().getDeclaredMethod(privateMethodName, privateArgClasses);

method.setAccessible(true);

String className = "Person";
String classPath = "C:\\workspace";

Object[] params = new Object[]{className, classPath};        

//note the return type of function 'getSamePackagePathAndName' is a String, so we cast
//the return type here as a string
String answer=  (String)method.invoke(inspectionTree, params);

method.setAccessible(false);
于 2013-10-02T12:30:46.950 回答