Sub topic 14
Method handles compared with Method.invoke
This chapter assumes you can already look up a Method, call it with Method.invoke, and handle checked exceptions. It adds java.lang.invoke.MethodHandle, which is a second way to call code you find at runtime. You will see how to create one, how it differs from Method.invoke, and when the difference matters.
What a method handle is
A MethodHandle is a typed, directly executable reference to a method, constructor, or field accessor. Method is a description of a member that you can ask to run. A MethodHandle is closer to a function pointer that the JVM knows how to call.
Two differences follow from this:
- Access is checked once, at lookup time. You get a handle through a
MethodHandles.Lookupobject. The lookup checks whether its creator may see the member. After that, calls through the handle do no per-call access check. - The handle has a type. Its
MethodTypeis a return type plus parameter types. The JVM can use that fixed signature to optimize calls.
Looking up and calling a handle
The lookup object records the class that created it. Whatever that class could access directly, the lookup can access too.
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 output is 10. Note these details:
MethodType.methodType(int.class)means "returnsint, takes no parameters". For an instance method,findVirtualadds the receiver as an extra leading parameter. The handle's full type is therefore(String)int.invokeExactis declaredthrows Throwable, so the caller must declare or catch it.- The
(int)cast is part of the call. The compiler records it as the call site's return type.
Lookup methods you will use most often:
| Method | Finds |
|---|---|
| `findVirtual` | An instance method. The receiver becomes the first argument. |
| `findStatic` | A static method. |
| `findConstructor` | A constructor. The handle returns the new object. |
| `findGetter`, `findSetter` | A field read or write. |
| `unreflect` | A handle for an existing `Method` object. |
invokeExact, invoke, and signature matching
invokeExact is strict. The static types at the call site must match the handle's type exactly, including the return type. A call whose types differ throws WrongMethodTypeException at run time. The compiler cannot catch this, because invokeExact is special: it is signature polymorphic, so the compiler builds the call's type from the arguments and the cast you write.
invoke is lenient. It first adapts the handle to the call site's type with asType, which can box, unbox, widen, and cast references. Adaptation costs a little, and the JIT compiler can often remove that cost when the handle is constant.
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.WrongMethodTypeException;
public class HandleBehavior {
static class Parser {
public int parse(String s) {
return Integer.parseInt(s);
}
}
public static void main(String[] args) throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle parse = lookup.findVirtual(
Parser.class, "parse",
MethodType.methodType(int.class, String.class));
MethodHandle bound = parse.bindTo(new Parser());
int ok = (int) bound.invokeExact("42");
System.out.println(ok);
Object arg = "42";
try {
int bad = (int) bound.invokeExact(arg);
System.out.println(bad);
} catch (WrongMethodTypeException e) {
System.out.println("invokeExact rejected Object argument");
}
Object adapted = bound.invoke(arg);
System.out.println(adapted);
try {
int unused = (int) bound.invokeExact("x");
System.out.println(unused);
} catch (NumberFormatException e) {
System.out.println("thrown directly: " + e.getClass().getSimpleName());
}
}
}The output is:
42
invokeExact rejected Object argument
42
thrown directly: NumberFormatExceptionThis program shows four things:
bindTofixes the first argument, here the receiver. The resulting handle has type(String)int.invokeExact(arg)fails becausearghas static typeObject, notString. The object inside is aString, but only the declared type counts.invoke(arg)succeeds. It castsObjecttoStringand boxes theintresult toObject.- An exception thrown by the target method reaches your code as is. There is no
InvocationTargetExceptionto unwrap, unlikeMethod.invoke.
How the two call paths differ
The main differences are:
| Aspect | `Method.invoke` | `MethodHandle` |
|---|---|---|
| Access check | On each call, unless `setAccessible(true)` was used | Once, at lookup |
| Arguments | `Object...`, so primitives are boxed and an array is allocated | Typed, with no array or boxing when the call site matches |
| Return value | `Object` | The handle's declared return type |
| Exceptions from target | Wrapped in `InvocationTargetException` | Thrown unchanged |
| Declared exceptions | `IllegalAccessException`, `InvocationTargetException` | `Throwable` |
| Composition | None | `bindTo`, `insertArguments`, `filterReturnValue`, `asType` |
| API style | Ordinary methods, easy to read | Signature-polymorphic calls, harder to read |
Performance: what is true and what is not
A MethodHandle is not automatically faster than Method.invoke. The speed advantage depends on one condition: the JIT compiler must be able to treat the handle as a constant. That is the case when the handle is stored in a static final field. The JIT can then inline the target into the caller, and the call costs about the same as a direct call.
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
public class CompareDemo {
private static final MethodHandle MAX;
static {
try {
MAX = MethodHandles.lookup().findStatic(
Math.class, "max",
MethodType.methodType(int.class, int.class, int.class));
} catch (ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
}
}
public static void main(String[] args) throws Throwable {
Method m = Math.class.getMethod("max", int.class, int.class);
Object viaReflection = m.invoke(null, 3, 7);
int viaHandle = (int) MAX.invokeExact(3, 7);
System.out.println(viaReflection + " " + viaHandle);
}
}Both calls print 7. The reflective call boxes 3 and 7 into an Object[] and returns an Integer. The handle call passes two int values and returns an int.
If you keep the handle in a non-final instance field or a local variable, the JIT sees an unknown handle and cannot inline through it. Such a call is slower, and it can be no faster than reflection. Handles held in a Map or fetched on each request often lose their advantage for this reason.
A version note applies here. In Java 11, Method.invoke starts with a slow native accessor and switches to generated bytecode after about 15 calls. From JDK 18, Method.invoke is itself implemented on top of method handles (JEP 416). The gap between the two shrinks on newer JDKs, so measure on the JDK you ship. Use a benchmark harness such as JMH. A simple timing loop in main is dominated by JIT warm-up and gives misleading numbers.
Access and modules
setAccessible(true) does not apply to handles. A Lookup carries the access rights of the class that created it. To reach a private member of another class, you have two options:
- Call
MethodHandles.privateLookupIn(targetClass, MethodHandles.lookup()), available since Java 9. It succeeds only if the target's module is open to your module. Otherwise it throwsIllegalAccessException. - Call
setAccessible(true)on aFieldorMethod, then pass it tounreflect,unreflectGetter, orunreflectSetter. The resulting handle keeps that access.
Both routes follow the same module rules you saw earlier. A handle does not bypass strong encapsulation.
Common mistakes
- Using
invokeExactwith anObjectvariable or a missing cast, which causesWrongMethodTypeException. - Forgetting that
findVirtualadds the receiver. A handle forString.length()takes one argument, aString, not zero. - Storing handles in non-final fields and expecting inlining.
- Catching
InvocationTargetExceptionaround handle calls. It is never thrown there, so the compiler will not even allow the catch unless something else in thetrythrows it. - Using
invokeWithArgumentsin hot code. It accepts a list of arguments and adapts them each time, so it is about as slow as plain reflection.
Exercise
A MethodHandle named h has type (String,int)String, found with findVirtual on String.substring(int) ... wait, check the type: what is the actual type of the handle for String.substring(int), and which cast must you write when calling it with invokeExact?
Show answer
The handle type is (String,int)String: the receiver String comes first, then the int parameter, and the return type is String. The call is String r = (String) h.invokeExact("reflection", 4);. The arguments must have static types String and int, and the result must be cast to String. If you pass an Object variable as the first argument or an Integer as the second, invokeExact throws WrongMethodTypeException, whereas invoke would adapt them.
Exercise
A method called through Method.invoke throws IllegalStateException. Through a MethodHandle, the same method is called. What exception type does your catch block need in each case to see the original error?
Show answer
With Method.invoke, the error arrives wrapped in InvocationTargetException, so you catch that and call getCause() to get the IllegalStateException. With a MethodHandle, the IllegalStateException is thrown directly and you can catch it by its own type, or catch Throwable because the call is declared that way.