Method handles
A MethodHandle is a typed, directly executable reference to a method, constructor or field. It does what reflection's Method.invoke does, but access is checked once when the handle is created, and the JIT can optimize a call through a constant handle like an ordinary call. This page explains the pieces of java.lang.invoke, looks up and invokes handles, combines them into new behaviour, builds a lambda the way invokedynamic does, and measures handles against direct calls and reflection.
Contents
What java.lang.invoke provides Looking up and invoking handles Fields, VarHandles and access checks Combinators: building behaviour from handles A lambda built by hand, and mutable call sites Method handles versus direct calls and reflection Pitfalls when working with handles Choosing between handles, reflection and lambdas
What java.lang.invoke provides
The java.lang.invoketoStringequalshashCode
: a signature, written return type first, such asMethodType formethodType(int.class, String.class) .int f(String) : a factory for handles that carries the access rights of the class that created it. Access is checked when a handle is looked up, never again at call time.MethodHandles.Lookup : the callable reference. ItsMethodHandle andinvokeExact methods are signature polymorphic: the compiler records the argument and return types used at each call site, and the JVM checks them against the handle's type.invoke : the target of anCallSite instruction, which a bootstrap method links to a handle the first time it runs.invokedynamic
| Method | Since | Finds |
|---|---|---|
findStaticfindVirtualfindConstructor | Java 7 | Static methods, instance methods (receiver becomes the first argument), constructors |
findSpecial | Java 7 | A specific superclass implementation, as super.m() |
findGetterfindSetterfindStaticGetterfindStaticSetter | Java 7 | Field access as handles |
unreflectunreflectGetter | Java 7 | Handles from reflection objects |
privateLookupInfindVarHandle | Java 9 | Full access to another class you may access deeply; field handles with atomic modes |
defineHiddenClass | Java 15 | Defining a hidden class, as the lambda machinery does |
Signature polymorphism is what makes handles fast. A call such as (int) mh.invokeExact("x")(String)int
The examples here ran on JDK 21.
Looking up and invoking handles
The program looks up a static method, an instance method of String
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.WrongMethodTypeException;
import java.util.ArrayList;
import java.util.List;
public class HandleBasics {
static int square(int x) {
return x * x;
}
private String greet(String name) {
return "hello " + name;
}
public static void main(String[] args) throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
// findStatic: class, name, and an exact type (return type first)
MethodHandle sq = lookup.findStatic(HandleBasics.class, "square",
MethodType.methodType(int.class, int.class));
System.out.println("square(7) = " + (int) sq.invokeExact(7));
// findVirtual: the receiver becomes the first argument
MethodHandle len = lookup.findVirtual(String.class, "length",
MethodType.methodType(int.class));
System.out.println("\"handles\".length() = " + (int) len.invokeExact("handles"));
// The lookup has this class's access rights, so private members are reachable
MethodHandle greet = lookup.findVirtual(HandleBasics.class, "greet",
MethodType.methodType(String.class, String.class));
System.out.println(greet.invoke(new HandleBasics(), "ada"));
// Constructors and fields
MethodHandle newList = lookup.findConstructor(ArrayList.class,
MethodType.methodType(void.class));
@SuppressWarnings("unchecked")
List<String> list = (List<String>) newList.invoke();
list.add("x");
System.out.println("constructed: " + list);
// invokeExact demands the exact static types at the call site
try {
Object wrong = sq.invokeExact(7); // returns Object instead of int
System.out.println(wrong);
} catch (WrongMethodTypeException e) {
System.out.println("invokeExact with wrong return type: WrongMethodTypeException");
}
System.out.println("invoke adapts types instead: " + sq.invoke(Integer.valueOf(7)));
}
}
Output:
square(7) = 49
"handles".length() = 7
hello ada
constructed: [x]
invokeExact with wrong return type: WrongMethodTypeException
invoke adapts types instead: 49
needs the exact type:findStatic formethodType(int.class, int.class) . A wrong type fails at lookup withint square(int) .NoSuchMethodException- For
, the receiver becomes the first argument, so the length handle has typefindVirtual and is called as(String)int .len.invokeExact("handles") - The private
was reachable because the lookup was created inside the same class and carries its private access.greet compiled with aninvokeExact result failed withObject : the call site's typeWrongMethodTypeException did not match the handle's(int)Object . The cast(int)int in front of the call is not decoration, it is part of the call's type.(int) is more forgiving: it adapts by boxing, unboxing and casting, here accepting aninvoke , at a small extra cost.Integer
Fields, VarHandles and access checks
An account class with private fields and a private method is accessed through four different lookups, which shows when access is granted and when it is refused.
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.VarHandle;
public class FieldsAndAccess {
static class Account {
private long balance = 100;
private static int created;
private void audit(String what) {
System.out.println(" audit: " + what + " on balance " + balance);
}
}
// A helper in another class: it has no right to Account's private members
static class Outsider {
static MethodHandles.Lookup lookup() {
return MethodHandles.lookup();
}
}
public static void main(String[] args) throws Throwable {
MethodHandles.Lookup mine = MethodHandles.lookup();
Account acc = new Account();
// Field getters and setters, typed like methods: (Account)long and (Account,long)void
MethodHandle get = mine.findGetter(Account.class, "balance", long.class);
MethodHandle set = mine.findSetter(Account.class, "balance", long.class);
set.invokeExact(acc, 250L);
System.out.println("getter type " + get.type() + ", value " + (long) get.invokeExact(acc));
MethodHandle created = mine.findStaticGetter(Account.class, "created", int.class);
System.out.println("static getter: " + (int) created.invokeExact());
// A VarHandle (Java 9) adds atomic access modes on the same field
VarHandle vh = mine.findVarHandle(Account.class, "balance", long.class);
System.out.println("VarHandle getAndAdd old value: " + (long) vh.getAndAdd(acc, 50L)
+ ", now " + (long) vh.get(acc));
// Access is checked against the Lookup, once, when the handle is created
MethodType auditType = MethodType.methodType(void.class, String.class);
MethodHandles.Lookup outsider = Outsider.lookup();
System.out.println("lookup class of the outsider: "
+ outsider.lookupClass().getSimpleName());
try {
MethodHandles.publicLookup().findVirtual(Account.class, "audit", auditType);
} catch (IllegalAccessException e) {
System.out.println("publicLookup() and a private method: IllegalAccessException");
}
// Nested classes are nestmates (Java 11), so the outsider's lookup may see it
MethodHandle audit = outsider.findVirtual(Account.class, "audit", auditType);
audit.invokeExact(acc, "nestmate call");
// privateLookupIn (Java 9): full access to another class in a module you can read
MethodHandles.Lookup deep = MethodHandles.privateLookupIn(Account.class, mine);
System.out.println("privateLookupIn has PRIVATE access: "
+ ((deep.lookupModes() & MethodHandles.Lookup.PRIVATE) != 0));
}
}
Output:
getter type (Account)long, value 250
static getter: 0
VarHandle getAndAdd old value: 250, now 300
lookup class of the outsider: Outsider
publicLookup() and a private method: IllegalAccessException
audit: nestmate call on balance 300
privateLookupIn has PRIVATE access: true
- A field getter has the type of a method that takes the object and returns the value,
; a setter is(Account)long . The setter changed the balance to 250 and the getter read it back.(Account,long)void - A
on the same field adds atomic operations:VarHandle returned the old 250 and left 300. ThegetAndAddVarHandle page covers all of its access modes. has only public access, so the private method was refused withpublicLookup() , at lookup time.IllegalAccessException- The
's own lookup could findOutsider 's private method. Both are nested inAccount , so they are nestmates (Java 11, JEP 181) and may access each other's private members, in the language and through handles alike. A top-level class in another file would have been refused.FieldsAndAccess (Java 9) produced a lookup with full private access toprivateLookupIn(Account.class, lookup) . It works when the caller's module can read the target module and the target package is open to it, which is always true within the class path's unnamed module.Account
Combinators: building behaviour from handles
The MethodHandles
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public class Transform {
static String format(String label, int value) {
return label + "=" + value;
}
static boolean isPositive(int x) {
return x > 0;
}
static String positive(int x) {
return "positive " + x;
}
static String notPositive(int x) {
return "not positive " + x;
}
public static void main(String[] args) throws Throwable {
MethodHandles.Lookup l = MethodHandles.lookup();
MethodHandle fmt = l.findStatic(Transform.class, "format",
MethodType.methodType(String.class, String.class, int.class));
// bindTo / insertArguments: fix some arguments (partial application)
MethodHandle score = MethodHandles.insertArguments(fmt, 0, "score");
System.out.println(score.invoke(42));
// filterArguments: transform an argument before the call
MethodHandle len = l.findVirtual(String.class, "length", MethodType.methodType(int.class));
MethodHandle lengthOf = MethodHandles.filterArguments(fmt, 1, len);
System.out.println(lengthOf.invoke("chars", "abcdef"));
// dropArguments: ignore an extra argument
MethodHandle ignoring = MethodHandles.dropArguments(score, 1, String.class);
System.out.println(ignoring.invoke(7, "ignored"));
// guardWithTest: an if/else built from handles
MethodHandle test = l.findStatic(Transform.class, "isPositive",
MethodType.methodType(boolean.class, int.class));
MethodHandle yes = l.findStatic(Transform.class, "positive",
MethodType.methodType(String.class, int.class));
MethodHandle no = l.findStatic(Transform.class, "notPositive",
MethodType.methodType(String.class, int.class));
MethodHandle choose = MethodHandles.guardWithTest(test, yes, no);
System.out.println(choose.invoke(5) + ", " + choose.invoke(-3));
System.out.println("type of choose: " + choose.type());
}
}
Output:
score=42
chars=6
score=7
positive 5, not positive -3
type of choose: (int)String
fixed the label to "score", turninginsertArguments into(String,int)String : partial application.(int)String does the same for the first argument when it is an object.bindTo ranfilterArguments on the second argument before the call, so passing "abcdef" printedString.length .chars=6 added an ignoreddropArguments parameter, which is how handles are adapted to a call site that passes more arguments than the target needs.String built an if/else: the test decided between the two targets, giving "positive 5" and "not positive -3", and the combined handle has typeguardWithTest . Dynamic language runtimes use exactly this to cache a fast path guarded by a type check. Others include(int)String ,catchException ,foldArguments and, since Java 9,permuteArguments andloop .tryFinally
A lambda built by hand, and mutable call sites
For a lambda or method reference, javacinvokedynamicLambdaMetafactory.metafactoryFunction
import java.lang.invoke.CallSite;
import java.lang.invoke.LambdaMetafactory;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MutableCallSite;
import java.util.function.Function;
public class LambdaByHand {
static String shout(String s) {
return s.toUpperCase() + "!";
}
static String whisper(String s) {
return s.toLowerCase() + "...";
}
public static void main(String[] args) throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodType strToStr = MethodType.methodType(String.class, String.class);
MethodHandle target = lookup.findStatic(LambdaByHand.class, "shout", strToStr);
// What javac's invokedynamic does for Function<String, String> f = LambdaByHand::shout
CallSite site = LambdaMetafactory.metafactory(lookup,
"apply", // interface method name
MethodType.methodType(Function.class), // factory: () -> Function
MethodType.methodType(Object.class, Object.class),// erased signature of apply
target, // the implementation
strToStr); // the real signature
@SuppressWarnings("unchecked")
Function<String, String> f = (Function<String, String>) site.getTarget().invokeExact();
System.out.println("hand-made lambda: " + f.apply("hello"));
System.out.println("its class is hidden: " + f.getClass().isHidden());
// A MutableCallSite can be re-pointed later: the idea behind dynamic languages
MutableCallSite mutable = new MutableCallSite(target);
MethodHandle invoker = mutable.dynamicInvoker();
System.out.println("call site now: " + (String) invoker.invokeExact("hey"));
mutable.setTarget(lookup.findStatic(LambdaByHand.class, "whisper", strToStr));
System.out.println("after setTarget: " + (String) invoker.invokeExact("HEY"));
// String concatenation is also compiled to invokedynamic (Java 9, JEP 280)
int n = 3;
System.out.println("concat result: " + ("n=" + n + ", f=" + f.apply("x")));
}
}
Output:
hand-made lambda: HELLO!
its class is hidden: true
call site now: HEY!
after setTarget: hey...
concat result: n=3, f=X!
- The arguments are what the compiler would pass: the interface method name
, a factory type returningapply , the erased signatureFunction , the implementation handle and the real signature(Object)Object . The resulting call site's target is a factory; invoking it gave a(String)String whose class is hidden, exactly like a compiled lambda.Function - A
'sMutableCallSite always calls the site's current target. AfterdynamicInvoker() , the same invoker whispered instead of shouting. The JIT inlines the current target and deoptimizes when it changes, which is how JRuby and Nashorn-style runtimes relink calls when a method is redefined.setTarget - The concatenation
also compiles to"n=" + n + ", f=" + ... withinvokedynamic as bootstrap since Java 9;StringConcatFactory on the class shows it.javap -c
Method handles versus direct calls and reflection
A trivial static method is called 20 million times directly, through a static finalMethod.invoke
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.util.Random;
public class HandleSpeed {
static int addOne(int x) {
return x + 1;
}
static final MethodHandle CONSTANT_MH;
static MethodHandle mutableMh;
static final Method METHOD;
static final int[] DATA = new Random(42).ints(1024, 0, 1000).toArray();
static {
try {
CONSTANT_MH = MethodHandles.lookup().findStatic(HandleSpeed.class, "addOne",
MethodType.methodType(int.class, int.class));
mutableMh = CONSTANT_MH;
METHOD = HandleSpeed.class.getDeclaredMethod("addOne", int.class);
} catch (ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
}
}
interface Body {
int run(int n) throws Throwable;
}
static double nsPerCall(Body body, int n) throws Throwable {
long best = Long.MAX_VALUE;
for (int r = 0; r < 5; r++) {
long t0 = System.nanoTime();
body.run(n);
best = Math.min(best, System.nanoTime() - t0);
}
return (double) best / n;
}
public static void main(String[] args) throws Throwable {
int n = 20000000;
System.out.printf("%,d calls, best of 5 runs%n", n);
System.out.printf("direct call: %6.2f ns%n", nsPerCall(k -> {
int acc = 0;
for (int i = 0; i < k; i++) {
acc += addOne(DATA[i & 1023]);
}
return acc;
}, n));
System.out.printf("static final MethodHandle: %6.2f ns%n", nsPerCall(k -> {
int acc = 0;
for (int i = 0; i < k; i++) {
acc += (int) CONSTANT_MH.invokeExact(DATA[i & 1023]);
}
return acc;
}, n));
System.out.printf("non-final MethodHandle: %6.2f ns%n", nsPerCall(k -> {
int acc = 0;
for (int i = 0; i < k; i++) {
acc += (int) mutableMh.invokeExact(DATA[i & 1023]);
}
return acc;
}, n));
System.out.printf("Method.invoke (reflection): %6.2f ns%n", nsPerCall(k -> {
int acc = 0;
for (int i = 0; i < k; i++) {
acc += (int) METHOD.invoke(null, DATA[i & 1023]);
}
return acc;
}, n));
}
}
Output (2-CPU Linux machine, JDK 21, best of 5):
20,000,000 calls, best of 5 runs
direct call: 0.27 ns
static final MethodHandle: 0.26 ns
non-final MethodHandle: 2.01 ns
Method.invoke (reflection): 3.73 ns
- The
handle was as fast as a direct call. Because the field is constant, the JIT treats the handle as a known target and inlinesstatic final right into the loop.addOne - The same handle in a non-final field was several times slower: the JIT must load the handle and dispatch through it on every call, because the field could change. Storing handles in
fields is the single most important rule for fast handle code.static final was the slowest here, though only by a few nanoseconds, since Java 18 implements it on top of method handles. It also boxes the argument and result, and checks access on every call unlessMethod.invoke was used.setAccessible(true)
Pitfalls when working with handles
- Exceptions pass through unchanged. A handle call declares
, so callers must catch or declare it, but the thrown exception is the target's own, not wrapped inthrows Throwable as with reflection.InvocationTargetException - A handle captures the access of its
. Passing a full-power lookup to untrusted code hands over the right to call every private member of your class; give outLookup or a lookup made withpublicLookup() instead.dropLookupMode on an interface or superclass method dispatches on the receiver's real class, like a normal virtual call. OnlyfindVirtual , which requires a lookup in the calling subclass, calls a particular implementation.findSpecial- Stack traces through combinators contain frames from
internals, which can make failures inside a long chain hard to read. Building the chain step by step and checking eachjava.lang.invoke helps.type()
Choosing between handles, reflection and lambdas
| Need | Use |
|---|---|
| Inspect classes, list members, read annotations | |
| Call a member chosen at run time, many times, fast | A MethodHandlestatic finalinvokeExact |
| Call a member chosen at run time, rarely | Reflection or MethodHandle.invoke |
| Turn a handle into an ordinary interface object | MethodHandleProxies.asInterfaceInstanceLambdaMetafactory |
| Atomic or ordered access to a field | |
| Runtime-generated behaviour without bytecode | Combinators such as guardWithTestfilterArguments |
| Implementing an interface dynamically |
See