Sub topic 14
Method handles compared with Method.invoke
This chapter assumes you can already look up a Method and call it with invoke, and that you know how setAccessible affects access checks. A method handle is a second way to call code by name at runtime, and it behaves differently from Method.invoke.
What a method handle is
A MethodHandle is a typed, directly executable reference to a method, constructor, or field. It lives in java.lang.invoke. You get one from a MethodHandles.Lookup object, and you describe the target's signature with a MethodType: the return type first, then the parameter types.
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public class HandleDemo {
public static void main(String[] args) throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle length = lookup.findVirtual(
String.class, "length", MethodType.methodType(int.class));
int n = (int) length.invokeExact("reflection");
System.out.println(n);
}
}The program prints 10. For an instance method, the receiver becomes the first argument of the handle. That is why invokeExact receives the string directly.
Where access is checked
Method.invoke checks access on every call, unless you turned the check off with setAccessible(true). A handle checks access once, when you call findVirtual. The Lookup object records what the calling class is allowed to see, so a handle can only reach members that the code creating the lookup could reach. Later calls skip that check.
invokeExact and invoke
invokeExact requires the call site's static types to match the handle's MethodType exactly, including the return type. The cast in (int) length.invokeExact(...) is part of that type. If you drop the cast or write (Object), the call site has a different type and the JVM throws WrongMethodTypeException at run time.
invoke is the forgiving version. It converts arguments by boxing, unboxing, and widening, so it is easier to use but slower than invokeExact.
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public class BindDemo {
public static void main(String[] args) throws Throwable {
MethodHandle length = MethodHandles.lookup().findVirtual(
String.class, "length", MethodType.methodType(int.class));
MethodHandle bound = length.bindTo("handles");
Object result = bound.invoke();
System.out.println(result);
}
}bindTo fixes the first argument, so bound takes no arguments. Because the result is stored in an Object, invoke boxes the int for you. The output is 7.
Comparison
| Aspect | `Method.invoke` | `MethodHandle` |
|---|---|---|
| Access check | On each call | At lookup time |
| Typing | Arguments as `Object...`, boxed | Typed call site |
| Exceptions from target | Wrapped in `InvocationTargetException` | Thrown as they are |
| Adaptation | None | Binding, argument reordering, composition |
| Speed when the handle is in a `static final` field | Slower | Can be inlined by the JIT |
The speed advantage mostly appears when the handle is stored in a static final field, where the JIT treats it as a constant. A handle kept in an ordinary local or instance field often performs about like reflection.
Common errors
- Writing
invokeExactwithout a matching cast, which givesWrongMethodTypeException. - Forgetting that
invokeExactandinvokethrowThrowable, so the calling method must declare it. - Passing the wrong
MethodType, which givesNoSuchMethodExceptionat lookup.
Exercise
Why does Object o = (Object) length.invokeExact("reflection"); fail for a handle of type (String)int, and how would you make the call succeed without changing the handle?
Show answer
invokeExact needs the call site's types to match the handle's type exactly. Casting the result to Object makes the call site's type (String)Object, which differs from (String)int, so it throws WrongMethodTypeException. Either cast to int ((int) length.invokeExact("reflection")) or call length.invoke("reflection"), which adapts the return type.