Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

There are 2 ways i have tried to obtain the MethodHandle to a given 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 both of them?

like image 661
wolfram77 Avatar asked Apr 09 '15 12:04

wolfram77


People also ask

What is the return type of lookup () method?

The parameter types of the method handle will be those of the constructor, while the return type will be a reference to the constructor's class. The constructor and all its argument types must be accessible to the lookup class.

What is a method handle?

A method handle is a typed, directly executable reference to an underlying method, constructor, field, or similar low-level operation, with optional transformations of arguments or return values. These transformations are quite general, and include such patterns as conversion, insertion, deletion, and substitution.


1 Answers

Obviously, unreflect has a resolved method already, therefore doesn’t need to do a lookup. Also, it’s output depends on the Method you provide, a static method will yield a handle invoking the static method while findVirtual explicitly request a virtual method invocation. Keep in mind that MyClass.class.getMethod("myMethod", String.class, Map.class) might also find a static method accepting a String and a Map.

Further, if setAccessible(true) has been applied to the Method instance, you may get a handle accessing an otherwise inaccessible method which is not possible using findVirtual.

On the other hand, findVirtual may find appropriately typed invocations of the signature polymorphic methods MethodHandle.invoke and MethodHandle.invokeExact which can’t be accessed via java.lang.reflect.Method.

like image 200
Holger Avatar answered Oct 23 '22 13:10

Holger