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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With