Video in progress

Strong Middle ⚙️ JVM and memory

How does calling a method through reflection work, how does it differ from MethodHandle, and what changed in Java 18?

Method.invoke checks access and arguments on every call and wraps the arguments in an array. A MethodHandle does the checks once, at creation, and if it sits in a static final field the JIT can inline it like an ordinary call. Since Java 18 (JEP 416), core reflection itself is also built on top of method handles internally.

📖 Answer

// Reflection
Method m = Order.class.getMethod("total");
Object r = m.invoke(order);            // Object[] args, boxing, checks

// MethodHandle
static final MethodHandle TOTAL;
static {
    try {
        TOTAL = MethodHandles.lookup()
                .findVirtual(Order.class, "total", MethodType.methodType(BigDecimal.class));
    } catch (ReflectiveOperationException e) { throw new ExceptionInInitializerError(e); }
}
BigDecimal r2 = (BigDecimal) TOTAL.invokeExact(order);  // exact type, no boxing

The differences:

  • Access checks. With reflection there is setAccessible and checks on every call. With a MethodHandle, access is checked once, based on where the Lookup was created.
  • Types. invokeExact requires the signature to match exactly and works without boxing.
  • JIT. A static final MethodHandle counts as a constant, so C2 inlines it directly. A handle in an ordinary field is slower.

Before Java 17, Method.invoke first used a native accessor, and after ~15 calls it "inflated" by generating bytecode, which meant a new class and metaspace use. JDK 18 replaced this mechanism with method handles: the code is simpler and there is no inflation. In most cases speed didn't change; in some cases (through a non-static Method object) it got slightly slower.

The practical takeaway: unless you write frameworks, you rarely need either. If you do need a dynamic call on a hot path, use a static final MethodHandle, or a functional interface through LambdaMetafactory.