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

There are two ways I tried to get the MethodHandle for this function.

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

What is the difference between the two?

+5
source share
1 answer

Obviously, unreflect already has a permitted method, so there is no need to search. In addition, its output depends on the Method you provide, the static method will give a handle to the static method, and findVirtual explicitly request a virtual method call. Keep in mind that MyClass.class.getMethod("myMethod", String.class, Map.class) can also find a static method that accepts String and Map .

Also, if setAccessible(true) was applied to the Method instance, you can get an access descriptor for a method that is not available in a different way, which is impossible with findVirtual .

On the other hand, findVirtual can find the corresponding typed calls of the polymorphic signature methods MethodHandle.invoke and MethodHandle.invokeExact , which cannot be accessed through java.lang.reflect.Method .

+3
source

All Articles