Scrivio Interview library
ConceptFoundations8 min read · updated 12 November 2026

Why is reflection usually slower than a direct method call? What changed in recent JDKs in how core reflection is implemented?

A reflective call such as method.invoke(target, args) does extra work that a direct call does not: it checks access, packs the arguments into an Object[] and boxes primitives, unboxes the result, and wraps any exception. It also hides the real target from the JIT compiler, which can inline a direct call but usually cannot see through a reflective one. Since JDK 18 (JEP 416), core reflection is built on method handles instead of generated accessor classes, which makes it simpler and lets warm calls through a constant Method run close to direct speed.

Why this question is asked

Reflection is everywhere in Java frameworks: Spring calls our @Bean and @EventListener methods with it, Jackson reads and writes fields with it, and JUnit finds and runs our test methods with it. Most of the time the cost does not matter, but in a hot loop it can show up clearly in a profiler. Interviewers ask this question to see whether we know where the cost really comes from, rather than repeating that reflection is slow. In this answer, we will recap what a reflective call is, walk through the extra work it does, see why the JIT treats it differently, look at what changed in JDK 18, and finish with how to measure it properly.

1A Quick Recap of Reflection

Reflection is the part of the JDK that lets a program look at classes at run time and use them without knowing them at compile time. Through java.lang.reflect we can ask a Class for its methods and fields by name, and then call a Method or read a Field on any object of that class.

A direct call is the normal kind, written in source code: greeter.greet("Ann"). The compiler knows the exact method, checks the argument types, and emits one invoke instruction. A reflective call does the same job, but every decision the compiler made ahead of time now has to be made at run time, on every call.

Java
class Greeter {
public String greet(String name) { return "Hi " + name; }
}
Greeter g = new Greeter();
String a = g.greet("Ann"); // Hi Ann: one invokevirtual instruction
Method m = Greeter.class.getMethod("greet", String.class); // lookup by name, done at run time
Object b = m.invoke(g, "Ann"); // Hi Ann: same result, much more work

Notice that the reflective version returns Object. The compiler no longer knows the return type, so we must cast it, and the cast itself is another run-time check.

2The Extra Work in Every Reflective Call

Let us follow what method.invoke(target, args) has to do that a direct call does not. First, it checks access: is the caller allowed to call this method? A public method of a public class passes quickly, and setAccessible(true) skips the check for later calls, but the check is still part of the path.

Second, it handles the arguments. invoke takes Object... args, so the compiler creates a new Object[] for every call, and every primitive argument is boxed: an int becomes an Integer. invoke then checks that each argument has the right type and unboxes it again before the real method runs. Third, the result comes back as Object, so a primitive return value is boxed as well. Fourth, if the target method throws, the exception is wrapped in an InvocationTargetException that we must unwrap.

Java
Method add = Math.class.getMethod("addExact", int.class, int.class);
Object r = add.invoke(null, 2, 3); // new Object[]{Integer.valueOf(2), Integer.valueOf(3)}, then unboxed
int sum = (Integer) r; // 5: the int result was boxed into an Integer and unboxed again
try {
add.invoke(null, Integer.MAX_VALUE, 1);
} catch (InvocationTargetException e) {
System.out.println(e.getCause()); // java.lang.ArithmeticException: integer overflow
}
Step throughWhat method.invoke() adds around the real call
  1. Check accessskipped after setAccessible(true)
  2. Pack argumentsnew Object[], primitives boxed
  3. Check and unbox argumentswrong type gives IllegalArgumentException
  4. Call the real methodthe only step a direct call needs
  5. Box the resultint becomes Integer
  6. Wrap exceptionsInvocationTargetException

6 steps in order. Play them, or step through them one at a time.

Only the highlighted step happens in a direct call.

So a single reflective call may allocate an array and several boxes, and run several type checks. Each is cheap on its own, but together they add up when the call runs millions of times.

3Why Lookups Must Be Cached

Finding the method is often more expensive than calling it. Class.getMethod("greet", String.class) has to search the class and its superclasses for a matching name and parameter list, run security and access checks, and return a fresh copy of the Method object every time, because Method objects are mutable (setAccessible changes them).

The fix is simple: look the Method up once and keep it, for example in a static final field or in a per-class cache. Code that calls getMethod or getDeclaredField inside a loop pays the search on every iteration, and that is the most common reason reflection shows up in a profile at all.

Java
// Slow: searches the class on every call
Object name(Object bean) throws Exception {
return bean.getClass().getMethod("getName").invoke(bean);
}
// Better: one lookup, reused for every call
private static final Method GET_NAME = lookup(); // found once when the class initialises
Object nameFast(Object bean) throws Exception {
return GET_NAME.invoke(bean);
}

4Why the JIT Can Inline Direct Calls but Not Reflective Ones

The JIT compiler, the part of the JVM that turns hot bytecode into machine code, gets most of its speed from inlining: it copies the body of a small called method into the caller. Once greet() is inlined, the JIT can remove the call overhead, keep values in registers and optimise both methods as one piece of code.

A direct call names its target in the bytecode, so the JIT knows what to inline. A reflective call goes into Method.invoke, which is a single shared method used for every Method in the program. From inside it, the target depends on which Method object we passed, and the JIT can only inline it if it can prove that the Method is a constant, for example when it comes from a static final field. When the Method comes from a map or a parameter, the call stays an indirect jump, and all the boxing around it usually stays too.

5What Changed in JDK 18: Reflection on Method Handles

Before JDK 18, Method.invoke had two strategies. For the first few calls (about 15 by default) it used a native accessor written in C++. After that, it generated a small class in bytecode, a so-called generated accessor (you may have seen GeneratedMethodAccessor in stack traces), which made the direct call for us. Field access had its own separate implementation based on Unsafe.

JEP 416 in JDK 18 replaced all of this with one implementation on top of method handles, the java.lang.invoke API that the JVM already optimises well because lambdas and string concatenation use it. Method, Constructor and Field now delegate to a direct method handle created for them. The JDK team did this mainly to remove duplicated, hard-to-maintain code, not to make every call faster.

The effect on speed depends on how the Method is held. When the JIT can treat it as a constant, the method handle can be inlined and the call is close to direct. When it cannot, the call can be about as fast as before or a little slower. Early releases kept a system property to switch back to the old implementation; it was later removed, so check your version if you depend on it.

Core reflection before and after JDK 18
AspectUp to JDK 17JDK 18 and later
Method.invokenative accessor, then generated bytecodedirect method handle
Field.get / setUnsafe-based accessorsmethod handles
First callsslow native path until inflationmethod handle from the start
Constant Method in static finalfast after inflationcan inline close to direct speed
Stack tracesGeneratedMethodAccessor framesDirectMethodHandleAccessor frames

6Measure It With JMH Instead of Guessing

Because the JIT can optimise warm reflective calls, a quick test with System.nanoTime() around a loop tells us very little: the first iterations run in the interpreter, the JIT may remove a loop whose result is unused, and garbage collection lands at random moments. JMH, the OpenJDK benchmark harness, handles warm-up, forks a fresh JVM, and gives us Blackhole to keep results alive.

The benchmark below compares a direct call, a cached Method and a lookup on every call. With -prof gc, JMH also shows bytes allocated per call, which reveals the boxing.

Java
@State(Scope.Benchmark)
public class ReflectBench {
Greeter g = new Greeter();
static final Method M;
static { try { M = Greeter.class.getMethod("greet", String.class); } catch (Exception e) { throw new Error(e); } }
@Benchmark public Object direct() { return g.greet("Ann"); }
@Benchmark public Object cachedMethod() throws Exception { return M.invoke(g, "Ann"); }
@Benchmark public Object lookupEachCall() throws Exception {
return Greeter.class.getMethod("greet", String.class).invoke(g, "Ann"); // usually much the slowest
}
}

Notice that only lookupEachCall pays for the search. In most real profiles, fixing that one mistake removes nearly all the cost.

7Follow-up questions

Does setAccessible(true) make reflection fast?

It removes the access check on each call, which helps a little, but it does nothing about the Object[] allocation, the boxing or the missing inlining. It also needs the package to be open to our module under the module system, otherwise it throws InaccessibleObjectException. It is not a performance tool so much as a way to reach non-public members.

When should we use a MethodHandle directly instead of Method?

When the call is hot and we can store the handle in a static final field. Then the JIT treats it as a constant and can inline through it, and invokeExact avoids boxing when the types match exactly. For occasional calls, such as reading annotations at startup, plain reflection is simpler and fast enough.

8Conclusion

In this answer, we saw that a reflective call is slower than a direct one because it checks access, allocates an argument array, boxes and unboxes values and wraps exceptions, and because the JIT can only inline it when the Method is a provable constant. Lookups by name are the biggest cost and should be done once and cached. Since JDK 18, Method, Constructor and Field are implemented with method handles instead of native and generated accessors, which simplifies the JDK and lets constant reflective calls run close to direct speed. And since the JIT changes the picture so much, we measure with JMH rather than guessing.

What to say in the interviewAbout 80 seconds aloud

Open with

A reflective call does several things a direct call skips. Method.invoke takes varargs, so every call builds an Object array and boxes primitive arguments, then checks their types and unboxes them; the result comes back boxed as Object; access is checked unless setAccessible was used; and exceptions are wrapped in InvocationTargetException.

Then, if they want more

The bigger issue is the JIT: a direct call names its target, so it can be inlined, but Method.invoke is one shared entry point, and the JIT can only see the real target if the Method is a constant, such as a static final field.

Lookups like getMethod by name are even more expensive, because they search the class hierarchy and copy the Method each time, so I always cache them. On the JDK side, since JDK 18, JEP 416 reimplemented core reflection on top of method handles instead of the old native accessor that switched to generated bytecode accessors after about fifteen calls.

That was mainly a maintenance change, but it means a constant Method can be optimised much like a method handle. Before changing anything for speed, I would measure with JMH, with warm-up and the gc profiler, because warm reflective calls are often faster than people expect.

About this answer

Last updated
12 November 2026
Versions it names
Java 18
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Why is reflection usually slower than a direct method call? What changed in recent JDKs...": https://scrivio-interview-library.netlify.app/java/reflection-and-method-handles/85fc97d535/