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

The java.lang.invoke package (Java 7, JSR 292) was added so that languages other than Java could run fast on the JVM. It then became the machinery behind several Java features: lambdas, string concatenation since Java 9 (JEP 280), the generated toString, equals and hashCode of records, and, since Java 18, core reflection itself (JEP 416). Its main types are:

  • MethodType: a signature, written return type first, such as methodType(int.class, String.class) for int f(String).
  • MethodHandles.Lookup: 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.
  • MethodHandle: the callable reference. Its invokeExact and invoke 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.
  • CallSite: the target of an invokedynamic instruction, which a bootstrap method links to a handle the first time it runs.
Lookup methods
MethodSinceFinds
findStatic, findVirtual, findConstructorJava 7Static methods, instance methods (receiver becomes the first argument), constructors
findSpecialJava 7A specific superclass implementation, as super.m() calls it
findGetter, findSetter, findStaticGetter, findStaticSetterJava 7Field access as handles
unreflect, unreflectGetterJava 7Handles from reflection objects
privateLookupIn, findVarHandleJava 9Full access to another class you may access deeply; field handles with atomic modes
defineHiddenClassJava 15Defining a hidden class, as the lambda machinery does

Signature polymorphism is what makes handles fast. A call such as (int) mh.invokeExact("x") is compiled with the descriptor (String)int taken from the call site, not from a declared signature, so no argument array is built and nothing is boxed. The price is strictness: the types written at the call site, including the cast on the result, must match the handle's type exactly.

The examples here ran on JDK 21.

Looking up and invoking handles

The program looks up a static method, an instance method of String, a private method of its own class and a constructor, and then calls one handle with the wrong static type to show what "exact" means.

Java
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:

Output
square(7) = 49
"handles".length() = 7
hello ada
constructed: [x]
invokeExact with wrong return type: WrongMethodTypeException
invoke adapts types instead: 49
  • findStatic needs the exact type: methodType(int.class, int.class) for int square(int). A wrong type fails at lookup with NoSuchMethodException.
  • For findVirtual, the receiver becomes the first argument, so the length handle has type (String)int and is called as len.invokeExact("handles").
  • The private greet was reachable because the lookup was created inside the same class and carries its private access.
  • invokeExact compiled with an Object result failed with WrongMethodTypeException: the call site's type (int)Object did not match the handle's (int)int. The cast (int) in front of the call is not decoration, it is part of the call's type. invoke is more forgiving: it adapts by boxing, unboxing and casting, here accepting an Integer, at a small extra cost.

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.

Java
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:

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, (Account)long; a setter is (Account,long)void. The setter changed the balance to 250 and the getter read it back.
  • A VarHandle on the same field adds atomic operations: getAndAdd returned the old 250 and left 300. The VarHandle page covers all of its access modes.
  • publicLookup() has only public access, so the private method was refused with IllegalAccessException, at lookup time.
  • The Outsider's own lookup could find Account's private method. Both are nested in FieldsAndAccess, 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.
  • privateLookupIn(Account.class, lookup) (Java 9) produced a lookup with full private access to Account. 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.

Combinators: building behaviour from handles

The MethodHandles class has dozens of static methods that take handles and return new ones, adapting arguments, fixing values or adding control flow, without generating any code yourself. A two-argument formatter and three small predicates are combined in four ways.

Java
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:

Output
score=42
chars=6
score=7
positive 5, not positive -3
type of choose: (int)String
  • insertArguments fixed the label to "score", turning (String,int)String into (int)String: partial application. bindTo does the same for the first argument when it is an object.
  • filterArguments ran String.length on the second argument before the call, so passing "abcdef" printed chars=6.
  • dropArguments added an ignored String parameter, which is how handles are adapted to a call site that passes more arguments than the target needs.
  • guardWithTest built an if/else: the test decided between the two targets, giving "positive 5" and "not positive -3", and the combined handle has type (int)String. Dynamic language runtimes use exactly this to cache a fast path guarded by a type check. Others include catchException, foldArguments, permuteArguments and, since Java 9, loop and tryFinally.

A lambda built by hand, and mutable call sites

For a lambda or method reference, javac emits an invokedynamic instruction whose bootstrap method is LambdaMetafactory.metafactory. The program calls that bootstrap method directly to create a Function from a method handle, then shows a call site whose target can be changed later.

Java
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:

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 apply, a factory type returning Function, the erased signature (Object)Object, the implementation handle and the real signature (String)String. The resulting call site's target is a factory; invoking it gave a Function whose class is hidden, exactly like a compiled lambda.
  • A MutableCallSite's dynamicInvoker() always calls the site's current target. After setTarget, 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.
  • The concatenation "n=" + n + ", f=" + ... also compiles to invokedynamic with StringConcatFactory as bootstrap since Java 9; javap -c on the class shows it.

Method handles versus direct calls and reflection

A trivial static method is called 20 million times directly, through a static final handle, through a handle in a non-final field, and with Method.invoke. The argument comes from an array so the JIT cannot fold the loop away. Best of 5 runs; a rough comparison, not a benchmark.

Java
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):

Output
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 static final handle was as fast as a direct call. Because the field is constant, the JIT treats the handle as a known target and inlines addOne right into the loop.
  • 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 static final fields is the single most important rule for fast handle code.
  • Method.invoke 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 unless setAccessible(true) was used.

Pitfalls when working with handles

  • Exceptions pass through unchanged. A handle call declares throws Throwable, so callers must catch or declare it, but the thrown exception is the target's own, not wrapped in InvocationTargetException as with reflection.
  • A handle captures the access of its Lookup. Passing a full-power lookup to untrusted code hands over the right to call every private member of your class; give out publicLookup() or a lookup made with dropLookupMode instead.
  • findVirtual on an interface or superclass method dispatches on the receiver's real class, like a normal virtual call. Only findSpecial, which requires a lookup in the calling subclass, calls a particular implementation.
  • Stack traces through combinators contain frames from java.lang.invoke internals, which can make failures inside a long chain hard to read. Building the chain step by step and checking each type() helps.

Choosing between handles, reflection and lambdas

Which mechanism to use for dynamic calls
NeedUse
Inspect classes, list members, read annotationsReflection
Call a member chosen at run time, many times, fastA MethodHandle in a static final field, called with invokeExact
Call a member chosen at run time, rarelyReflection or MethodHandle.invoke; either is fine
Turn a handle into an ordinary interface objectMethodHandleProxies.asInterfaceInstance, or LambdaMetafactory for speed
Atomic or ordered access to a fieldVarHandle
Runtime-generated behaviour without bytecodeCombinators such as guardWithTest and filterArguments
Implementing an interface dynamicallyDynamic proxies

See functional interfaces for how lambdas look from the language side, and bytecode instrumentation for changing classes themselves.