`lookup.unreflect()`和`lookup.findVirtual()`有什么区别?

时间:2015-04-09 12:43:21

标签: java reflection java-8

我尝试过两种方法来获取给定函数的MethodHandle。

  

方法1

Method m = MyClass.class.getMethod("myMethod", String.class, Map.class);
MethodHandle mh = MethodHandles.lookup().unreflect(m);
  

方法2

MethodType type = MethodType.methodType(void.class, String.class, Map.class);
MethodHandle mh = MethodHandles.lookup().findVirtual(MyClass.class, "myMethod", type);

两者之间有什么区别?

1 个答案:

答案 0 :(得分:3)

显然,unreflect 已经已经解析的方法,因此不需要进行查找。此外,它的输出取决于您提供的Methodstatic方法将产生调用static方法的句柄,而findVirtual显式请求虚拟方法调用。请注意,MyClass.class.getMethod("myMethod", String.class, Map.class)也可能会发现static方法接受StringMap

此外,如果已将setAccessible(true)应用于Method实例,您可能会获得一个句柄来访问使用findVirtual无法访问的其他无法访问的方法。

另一方面,findVirtual可能会找到签名多态方法MethodHandle.invokeMethodHandle.invokeExact的适当类型调用,这些方法无法通过{{{ 1}}。