Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Java method handles: lookup, binding, and invocation

Look up an instance method by its signature, bind the receiver into a new handle, and compare an exact call with a call that can adapt compatible types.

Version: Java SE 21

Syntax

Java SE 21 · java.lang.invoke
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodType signature = MethodType.methodType(String.class, int.class);
MethodHandle target = lookup.findVirtual(String.class, "substring", signature); // (String, int) -> String
MethodHandle bound = target.bindTo("Java");                                    // (int) -> String
String unboundResult = (String) target.invokeExact("Java", 1);
String boundResult = (String) bound.invokeExact(2);
String adaptedResult = (String) bound.invoke((byte) 2);
// The invocations declare throws Throwable.

In Java SE 21, method handles are part of java.lang.invoke. MethodHandles.lookup() creates a Lookup with the calling class's access privileges. MethodType.methodType(String.class, int.class) describes a String return and one int parameter, with no receiver. MethodHandles.Lookup.findVirtual looks up an instance method by class or interface, name, and that method type. A missing match gives NoSuchMethodException; denied access or a static target gives IllegalAccessException. Don't share a privileged Lookup with untrusted code.

The resulting handle prepends a receiver parameter: its type is usually the requested class or interface, but protected access rules can narrow it. For non-private methods, the receiver's runtime type determines which implementation runs. The three operations in MethodHandle.bindTo/invokeExact/invoke do different jobs. bindTo doesn't call the method: it creates a new fixed-arity handle that supplies a reference as the first argument. The original handle is unchanged. If there's no leading reference parameter, bindTo throws IllegalArgumentException; if the reference can't be converted to that parameter type, it throws ClassCastException.

invokeExact and invoke are signature-polymorphic: the arguments' static types determine the call site's parameter types. A bare null argument has the null type, which the compiler records as java.lang.Void in the call-site descriptor. So the argument in invokeExact(null) doesn't exactly match a String parameter; use (String) null to give the argument the static type String. An explicit cast on the call sets its return type; without a cast it's Object in an expression or void when the call stands alone as a statement. invokeExact requires this entire type to equal handle.type(). It performs no conversions and throws WrongMethodTypeException on a mismatch.

invoke behaves like invokeExact for an exact match; otherwise it attempts adaptation under asType rules. An unsupported adaptation throws WrongMethodTypeException. A permitted cast can still fail at runtime with ClassCastException, and unboxing null throws NullPointerException. Both invocation methods declare throws Throwable and can propagate exceptions from the target.

Examples

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

public class MethodHandleDemo {
    public static void main(String[] args) throws Throwable {
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodType signature = MethodType.methodType(String.class, int.class);
        MethodHandle substring = lookup.findVirtual(String.class, "substring", signature);

        String text = "Java";
        String unboundResult = (String) substring.invokeExact(text, 1);
        MethodHandle bound = substring.bindTo(text);
        String boundResult = (String) bound.invokeExact(2);

        byte index = 2;
        String adaptedResult = (String) bound.invoke(index);

        System.out.println(unboundResult);
        System.out.println(boundResult);
        System.out.println(adaptedResult);
    }
}

Result

ava
va
va

The lookup selects `substring(int)`, not `substring(int, int)`. The first `invokeExact` passes a `String` and an `int`; the second passes only an `int` because `bindTo` has fixed the receiver to `"Java"`. Both casts specify a `String` return. The final `invoke` widens `byte` to `int`, so it prints `va` just like the second call.

Related lessons

  • Java · Lesson 56 · Advanced · Version: 2

Sources