Lesson · Reflection, Proxies & Method Handles
MethodHandles & VarHandles: the call site the JIT can inline
12 min readMethodHandles & VarHandles
A MethodHandle is a typed reference to a method whose access is checked once, when the handle is created, and whose invocation then looks like an ordinary call. VarHandle points the same idea at a variable and lets you name the memory ordering of each access. Hidden classes are this layer seen from the class side.
The problem: reflection pays the same tax on every call
Reflection arrived first, and the reflection-basics lesson owns its shape: a Class object, getDeclaredMethod, then invoke with an Object[]. It reads like a lookup, and that is exactly what it is. Every call re-checks access, boxes the arguments, collects them into an array, and dispatches through a path the JIT cannot see through. One call is fine. A million calls is a design smell.
A MethodHandle, added in Java 7 by the same JSR 292 work that produced invokedynamic, splits that tax in two. The lookup half happens once, when you ask for the handle: lookup.findVirtual(String.class, "length", MethodType.methodType(int.class)) either returns a typed, immutable handle to that method or fails because your lookup class was not allowed to see it. The call half is then an ordinary call: invokeExact on a handle held in a static final field is a call site the JIT can inline like any other.
That is the whole trade. Reflection is a lookup that happens to call for you; a handle is a call that a lookup prepared for you.
- Typed: a handle carries a
MethodType, so arity and parameter types are part of the value you hold, not something reconstructed per call from anObject[]. - Immutable and thread safe: a handle has no visible state, so it can be published in a static field and shared without synchronisation.
- Created under a lookup: all access checking happens at creation, which is why the lookup object is treated as a capability (see the next section).
- Plain call sites:
invokeandinvokeExactare signature polymorphic, so after linking the call site is a real call with real types.
Reflection checks per call; a handle checks once and then behaves like a normal call site. That one sentence is the reason the API exists, and it also predicts where each one belongs: reflection for a few calls per process, handles for the calls that run in a loop.
Lookup: a door that decides what you may find
You never construct a handle directly. You ask a MethodHandles.Lookup object for one, and that object carries the access rights of the class that obtained it. MethodHandles.lookup() gives a caller full privilege access to its own class; MethodHandles.publicLookup() gives a lookup that can only reach public members of public classes in exported packages.
Which factory you call decides which kind of member you can name, and what the resulting handle's first parameter will be.
| Factory on Lookup | Names | Leading parameter of the handle |
|---|---|---|
findStatic(refc, name, type) | a static method | none |
findVirtual(refc, name, type) | an instance method | the receiver |
findSpecial(refc, name, type, specialCaller) | a private method, or a super call | the receiver |
findConstructor(refc, type) | a constructor | none |
findGetter / findSetter | a field | the receiver |
findVarHandle(refc, name, type) | a field, as a variable (Java 9) | the receiver as a coordinate |
- The lookup class owns the rights, not the caller. A private member needs a lookup with private access to that class; once the handle exists it can be handed to any code, because the decision was already made.
- Lookup modes form a ladder: PRIVATE, PACKAGE, PROTECTED, PUBLIC, plus MODULE since Java 9.
lookupModes()reports what you hold, which is how you tell a full-privilege lookup from a public one. - `MethodHandles.privateLookupIn(target, caller)` (Java 9) is the way into another package. It succeeds only if the caller lookup has full privilege access, the caller module reads the target module, and the target package is open to at least the caller module.
- The result is a capability, not a reference. Anyone holding a handle to a private member can call it, so keep such handles as private as the member itself; the reflection-encapsulation lesson covers what opening a package for this costs you.
A lookup is a door, and the door decides. The class that obtained it is the class whose bytecode rules apply, so a lookup created inside a class can name that class's private members, while publicLookup() can name almost nothing at all.
invokeExact, invoke, and signature polymorphism
MethodHandle.invokeExact and MethodHandle.invoke are signature polymorphic. The compiler emits an invokevirtual whose descriptor is the descriptor you wrote at the call site, and the JVM checks that descriptor against the handle's MethodType when the instruction links. There is no reflection left in the call: it is a call, with a box-free argument list if you asked for one.
The difference between the two is one word. invokeExact requires the descriptor to match exactly, so (int) length.invokeExact("hello") calls the method directly. Passing an int to a handle declared to take a long fails at runtime with WrongMethodTypeException, even though int widens to long in ordinary Java. invoke applies the asType conversions first (boxing, unboxing, primitive widening, reference casts), which makes it forgiving and less direct; it is the right default while you are wiring things up, and invokeExact is what you move to once the shape is fixed.
The two calls do not only differ in tone, they differ in what the JIT can promise itself.
| Call site | Descriptor | On mismatch | Where the conversion lives |
|---|---|---|---|
invokeExact(args) | must equal the handle's type exactly | WrongMethodTypeException at runtime | nowhere: you must already be exact |
invoke(args) | may differ from the handle's type | conversions are applied, then the call runs | asType semantics, applied by the JVM |
- Ask for a handle:
lookup.findVirtual(String.class, "length", MethodType.methodType(int.class))produces type(String)int. (int) length.invokeExact("hello")compiles to a descriptor of(String)int, matches the handle, and the body runs inline at the call site.handle.invoke("hello")compiles to(Object)Object; the JVM adapts the argument and boxes the result, so it still returns5.(long) length.invokeExact("hello")compiles to(String)longand throwsWrongMethodTypeException, because a widening that the source compiler would accept is not a match.- When you want the widening on purpose, ask for it:
length.asType(MethodType.methodType(long.class, String.class))returns an adapter that performs it.
- `asType(MethodType)` returns an adapter handle that converts arguments and the return value, the same conversions
invokeapplies silently. - `bindTo(value)` fixes the first argument, which for an instance method is the receiver, turning a
(T, A...)Rhandle into an(A...)Rone. - `insertArguments(handle, pos, values...)` bakes constants into chosen positions at build time, so the call site never sees them.
- The type check happens once per call site, at link time, not per invocation; that is why a loop over
invokeExactis not a loop of checks.
`invokeExact` is a promise about the descriptor, not about the values. Boxes, widenings and reference casts that the source language allows are exactly what it refuses, and asType is the place to put them, deliberately and visibly.
Combinators: build the call you want
Combinators take handles and return handles; nothing is invoked while you build. The core set (constant, identity, insertArguments, filterArguments, filterReturnValue, foldArguments, guardWithTest, catchException) shipped with Java 7, and Java 9 added the loop and try/finally combinators along with the lookup refinements (JEP 274).
The reason to build a chain instead of writing a lambda is the shape of the work. A chain is created once and then reused as a single call site: no lambda object per call, no captured state to rebuild, and the JIT sees one composed call rather than a factory call plus a dispatch.
| Combinator | What it inserts | Reach for it when |
|---|---|---|
filterArguments | a unary filter in front of chosen arguments | a value arrives in one type and must be passed in another |
filterReturnValue | a filter after the call, on the result | the caller wants a different type than the target returns |
foldArguments | a pre-processing step whose result becomes a leading argument | a tracing, logging or validation step belongs on every call |
guardWithTest | an if/then/else over one boolean handle | two implementations and one condition choose between them |
constant / identity | a fixed value, or the argument itself | a type must match and a slot must be filled |
tableSwitch | a branch on a leading int selector | dispatch on a small integer code, with a fallback |
- Mismatches surface when you build, not when traffic arrives. A combinator with incompatible types throws
IllegalArgumentExceptionat construction time, which is the cheapest possible moment to learn it. - A chain is one call site. Composing three handles once and storing the result in a
static finalfield gives the JIT a single thing to inline instead of a per-call composition. - Combinators are not a style choice. If a lambda expresses the same thing more clearly, write the lambda; the point of a chain is a call site that must be configured at run time and then reused.
Build the pipeline once, invoke it many times. A combinator chain assembled per request is a lambda with extra steps; the same chain assembled at startup and held in a static final field is a call site the runtime can optimise.
VarHandle: the same idea, aimed at a variable
A MethodHandle names a method. A VarHandle, part of Java 9 (JEP 193), names a variable: a non-static field, a static field, or an array element. It is the field and array equivalent of a handle, and the atomic classes are built on it. The access modes are the ones the JMM lessons describe, and the volatile lesson owns what a fence actually does; what belongs here is the ladder and the API.
The ladder is what you are buying. Each rung adds a guarantee and keeps the ones below it, and you pick the rung per access rather than per declaration.
| Access mode | Read / write pair | What it adds |
|---|---|---|
| plain | get / set | nothing: an ordinary access, bitwise atomic only for references and primitives up to 32 bits, with no ordering against other threads |
| opaque | getOpaque / setOpaque | coherence for this one variable: never a torn value, and other threads eventually see the write |
| acquire / release | getAcquire / setRelease | a release write orders the loads and stores before it; an acquire read orders the ones after it |
| volatile | getVolatile / setVolatile | both halves at once, totally ordered against other volatile operations on the same variable |
- A VarHandle is meant to be a constant. Keep it in a
static finalfield so the JIT can treat the access as a known operation and compile it into the load or store you asked for. - Coordinates come first: the receiver for an instance field, the array plus the index for an element, so one API covers both without a family of
getInt-style methods. - `get` and `set` are always supported; the rest are optional. A read-only variable (a
finalfield, for example) supports no write or update mode and throwsUnsupportedOperationExceptionif you try. - The access mode type is checked per access, unlike the handle's once-only check, and a mismatch is a
WrongMethodTypeException.withInvokeExactBehavior()(Java 16) makes that strict on purpose. - Compare-and-set lives here:
compareAndSetandcompareAndExchangecarry volatile semantics by default, and theAcquireandReleasevariants let you pay for less.
One declaration, several orderings: that is what a VarHandle is for. A volatile field is volatile for every access; a handle lets the writer pay for a release and the reader for an acquire, and nothing more.
Handles · the ladder and the path
no rung ever gives a guarantee back
VarHandle · what each access mode adds
both halves at once: an acquire read and a release write in one access, totally ordered against other volatile operations on the same variable
a release write orders the loads and stores before it; an acquire read orders the loads and stores after it
coherence for this one variable: never a torn value, other threads eventually see the write, still no ordering against other memory
nothing: an ordinary access, bitwise atomic only for references and primitives up to 32 bits, and no ordering at all
MethodHandle · from lookup to call site
MethodHandles.lookup()
the door: private access to the caller's own class. privateLookupIn(target, caller) crosses a package, and only when it is open to the caller's module.
findStatic / findVirtual / findSpecial / findGetter / findVarHandle
the kind you ask for decides the handle's type: a receiver parameter for an instance member, none for a static one.
handle.invokeExact(args)
the call site: the descriptor is checked against the handle's MethodType when the instruction links, then it is an ordinary call.
one idea, two targets
MethodHandle
names a method or constructor; the arguments are the parameters, and the first parameter of an instance handle is the receiver.
VarHandle
names a variable and an ordering; the coordinates locate it, and the access mode decides what the JVM may assume about the access.
A descriptor that differs by one widening or one boxing does not match, so invokeExact throws WrongMethodTypeException where invoke would have converted the arguments first. asType is how the conversion is asked for on purpose.
Hidden classes: where the runtime keeps its generated code
Handles, lambdas and proxies all end in a class the runtime generates for you. Those classes used to be VM-anonymous classes created through Unsafe::defineAnonymousClass. JEP 371 replaced them with hidden classes, final in JDK 15, created through Lookup.defineHiddenClass(bytes, initialize, options...).
A hidden class is not discoverable. Class.forName, a class loader, and a symbolic reference in another class file cannot reach it; only the Class object you received (or the lookup the definition call returned) can. It does have a name for diagnostics, but the name is not a binary name, getCanonicalName() returns null, and Class.isHidden() (Java 15) answers the question directly when a tool hands you something suspicious.
Two properties make it the right container for generated code: it can join the nest of the class that defined it, so generated code reads private members without synthetic accessors, and it can be unloaded when nothing refers to it, without dragging a class loader down with it.
- The visible users are the runtime's own tricks: lambda bodies (the lambda-internals lesson follows that path) and generated proxy classes (the dynamic-proxies lesson takes the other).
- Frameworks spin their own too: mocks, serializers, query implementations and accessor classes generated at startup are hidden classes when the framework is up to date.
- Stack traces leave them out unless you ask for them with
-XX:+UnlockDiagnosticVMOptions -XX:+ShowHiddenFrames; when a trace suddenly mentions a class you never wrote, that is a generated one you asked for indirectly. - You rarely call the API yourself. It exists so that a language runtime can create a class it can hold, share with a nestmate and then forget.
A hidden class is a class you can hold, not one you can name. That is the entire contract, and it is what lets generated code be an implementation detail instead of a public surface.
Choosing a mechanism, in one paragraph and one table
Reach for a plain call first, because it is one. When the member must be chosen at run time, ask what the cost would be: if you are scanning at startup and calling a few times, reflection is honest and clear; if the same call site runs in a loop or on every request, create a MethodHandle once and let the call be a call. When a volatile field or an atomic would express the operation, use them, because a VarHandle is for the cases they cannot express, not for the ones they can.
The lab below runs the four operations against the three mechanisms and shows where each one checks, what it can inline, and what it refuses.
| Operation | Reflection | MethodHandle | VarHandle |
|---|---|---|---|
| read a field | Field.get, boxed, checked per call | findGetter, then a call | get / getOpaque / getAcquire / getVolatile |
| write a field | Field.set, boxed on the way in | findSetter, then a call | set / setOpaque / setRelease / setVolatile |
| compare-and-set | not available: get, compare and set are three calls | not available on a plain handle | compareAndSet / compareAndExchange |
| call an interface method | Method.invoke with an Object[] | findVirtual, then invokeExact | not applicable: a handle names a variable |
- First: is a direct call possible? Compile-time dispatch beats every mechanism on this page, and interfaces plus
invokedynamiccover most of the rest. - Then ask how often the site runs. Once or twice per process: reflection. In a loop or per request: a handle created at startup.
- Then ask which half of the operation you are touching. A method or constructor is a
MethodHandle; a field or array element is aVarHandle; there is no overlap, and neither covers the other. - `invoke` while wiring, `invokeExact` once the shape is fixed. The forgiving call hides conversions that a later reader cannot see.
The mechanism follows the operation, and the operation follows the frequency. Nothing on this page is faster than a direct call, and nothing else can express a call whose target only exists at run time.
Mechanism lab · one operation, three ways
pick an operation and a mechanismoperation
mechanism
Works: findVirtual or findInterface, then a call at the site.
checked when
Once at lookup; then the descriptor at the call site is checked against the handle's type when it links.
what can inline
An exact descriptor on a constant handle gives the JIT a call site it can inline and devirtualise.
what it refuses
A descriptor that differs by a widening or a boxing fails at runtime even though it looks compatible in source. asType is the conversion, not the compiler.
recommendation: The case handles were built for: a call that is chosen at run time and then runs hot.
invokeExact does not convert anything
The descriptor at the call site has to match the handle's MethodType exactly, and the types that look compatible in source are the ones that fail at runtime: an int argument for a long parameter, a String for an Object parameter, a boxed Integer where a primitive is expected. Each of those is a legal conversion in ordinary Java, so the code reads as if it should work, and each throws WrongMethodTypeException at the call. invoke is the version that applies those conversions; asType is how you ask for them where you want them, so the widening is visible in the code instead of hiding inside the call.
Interview angles
Why reach for a MethodHandle instead of reflection?+
Because the two halves of the cost are separated: the access check, the name lookup and the type assembly happen once when you create the handle, and each invocation is then a plain call site the JIT can inline. Reflection re-checks and re-boxes on every call and stays opaque to the optimiser.
The places where this matters are boring and concrete: a mapped property read per row, a handler call per request, a comparison per element. All of them are call sites that run in a loop.
Common misconception: That MethodHandles are just a faster reflection API. They are a different model: reflection describes a member and asks it to be invoked, a handle is the invocation itself, typed and reusable.
What exactly does invokeExact require, and when does it fail?+
An exact match between the descriptor at the call site and the handle's MethodType. If they differ in any way, including a primitive widening or a boxing that the source language would have applied, the call throws WrongMethodTypeException at runtime.
The check is cheap because it happens once per call site, when the instruction links, not per invocation. That is also why the fix is structural: change the handle's type with asType, or change the descriptor you wrote.
int len = (int) length.invokeExact("hello"); // descriptor (String)int: exact, runs long big = (long) length.invokeExact("hello"); // descriptor (String)long: throws
Follow-up: Which call would you use in a generic utility that has to work with any handle? invoke, or an invoker obtained from MethodHandles.invoker(type).
Why is the lookup object called a capability?+
Because it carries the access rights of the class that obtained it, and it can be passed to code that has no rights of its own. Every handle created through it inherits a decision that was made once, in the context of that class.
MethodHandles.lookup() gives full privilege access to the caller's class, so handing it out is equivalent to handing out the ability to call private members. privateLookupIn(target, caller) is the sanctioned way to reach another package, and it only works if that package is open to the caller's module.
Common misconception: That the caller of findVirtual is the class whose access rules apply. It is the lookup class, wherever the call is eventually made from.
When would you use a VarHandle rather than declaring the field volatile?+
When the ordering is not the same for every access, when you cannot change the declaration (a field in another class, an array element, an off-heap location), or when you need an atomic read-modify-write such as compareAndSet on one variable.
The ladder is plain, opaque, acquire or release, volatile, and you choose per access. The volatile declaration commits every read and write of that field to the top rung.
Follow-up: Which Java version introduced VarHandle? Java 9, under JEP 193.