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

What is the difference between `lookup.unreflect()` and `lookup.findVirtual()`?

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

Method 1

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

Method 2

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

两者有什么区别?

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

static 方法

此外,如果 setAccessible(true) 已应用于 Method 实例,您可能会获得一个句柄来访问其他无法访问的方法,而使用 findVirtual.[=26= 则无法访问该方法]

另一方面,findVirtual 可能会找到 签名多态 方法 MethodHandle.invokeMethodHandle.invokeExact 的适当类型调用通过 java.lang.reflect.Method.

访问