CKTIS / Java
MethodHandle: argument binding and typed invocation
MethodHandle is a typed reference to an operation. Learn how bindTo binds its first argument and how strict invokeExact differs from type-adapting invoke in Java SE 21.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
MethodHandle bound = handle.bindTo(receiver);
String exact = (String) bound.invokeExact(intArgument);
Object adapted = bound.invoke(integerArgument);java.lang.invoke.MethodHandle represents an operation, such as a method. Its type is described by MethodType. MethodHandles.lookup().findVirtual creates a handle to an instance method; the receiver becomes the first argument. Access is checked when the handle is created, so a handle to a non-public method must be protected from untrusted code.
MethodHandle.bindTo(x) creates a new handle by binding x to the first parameter (position 0) only. That parameter must have a reference type. If the first parameter has a primitive type, bindTo throws IllegalArgumentException, even if a later parameter has a reference type. Binding neither invokes the operation nor changes the original handle. In the example, binding the receiver changes the type from (String,int)String to (int)String.
MethodHandle.invokeExact requires identical argument and return types at the call site; a mismatch causes WrongMethodTypeException. This is why the example uses (String) and an int argument. MethodHandle.invoke allows adaptation according to asType: here, unboxing Integer to int and returning the result as Object. This does not allow arbitrary conversions.
Both invocation methods declare throws Throwable. The example passes that obligation to main; application code should deliberately handle or propagate failures.
Examples
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public class Main {
public static void main(String[] args) throws Throwable {
MethodHandle substring = MethodHandles.lookup().findVirtual(
String.class, "substring",
MethodType.methodType(String.class, int.class));
MethodHandle bound = substring.bindTo("Java");
String exact = (String) bound.invokeExact(2);
Integer index = Integer.valueOf(1);
Object adapted = bound.invoke(index);
System.out.println(exact);
System.out.println(adapted);
}
}Result
va ava
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.