Sub topic 15
Performance, safety, and design pitfalls
This chapter assumes you have used Class, Field, Method, and setAccessible from the earlier chapters. Reflection works, but it costs speed, bypasses compile-time checks, and can break when the code around it changes. You will learn where those costs come from, how to reduce them, and when to choose another tool.
Where the performance cost comes from
A normal method call is resolved and checked when the program is compiled, and the JIT compiler can inline it. A reflective call does more work at run time:
- Lookup.
getMethodandgetDeclaredFieldsearch the class's members by name and parameter types. Each call returns a fresh copy of theMethodorFieldobject. - Access checks.
invokechecks whether the caller may use the member, unlesssetAccessible(true)was called. - Argument handling. Arguments travel in an
Object[]. Primitives are boxed on the way in and out, and the argument count and types are checked on every call. - Weak inlining. The JIT often cannot treat a
Method.invokecall as a direct call, so the optimizations that make ordinary calls fast do not apply.
Lookup is usually the largest avoidable cost, and you can remove it by caching. Do the lookup once, store the result, and call it many times.
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class CachedLookup {
private static final Map<String, Method> CACHE = new ConcurrentHashMap<>();
static Method findNoArgMethod(Class<?> type, String name) {
return CACHE.computeIfAbsent(type.getName() + "#" + name, key -> {
try {
return type.getMethod(name);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("No method " + key, e);
}
});
}
public static void main(String[] args) throws Exception {
Method length = findNoArgMethod(String.class, "length");
System.out.println(length.invoke("reflection"));
System.out.println(findNoArgMethod(String.class, "length") == length);
}
}The program prints 10 and then true. The second lookup returns the cached object, so no new search happens.
Call setAccessible(true) once, when you cache the member, not before every call.
Method handles on hot paths
Method.invoke re-checks and re-boxes on every call. A MethodHandle does its access check when you look it up, and the JIT can optimize calls through it. The best case is a handle stored in a static final field, because the JIT then treats it as a constant and can inline the call. A handle in an ordinary instance field or a local variable loses most of that advantage.
Handles have costs of their own. invokeExact fails at run time with WrongMethodTypeException if the call site's types differ even slightly from the handle's type, including a missing cast on the return value. The API is also harder to read. Use handles when profiling shows that reflective calls are a bottleneck. For one-time setup code, Method.invoke is simpler.
Safety: what the compiler no longer checks
Reflection replaces compile-time checks with names stored in strings. Each of the following moves an error from compile time to run time.
- Renames break silently. If you rename
greettosayHello, the string"greet"still compiles. The failure is aNoSuchMethodExceptionin production. - Types are unchecked.
invokeacceptsObjectarguments and returnsObject. A wrong argument type becomes anIllegalArgumentExceptionwhen the call executes. - Encapsulation is bypassed.
setAccessible(true)lets you change private state that the class's author never meant to expose. The class can then end up in states its own code never expected. - Optimizations are bypassed. The compiler inlines constants, so a reflective write may not be seen by compiled code.
The last point is easy to miss. This example writes to a final field successfully, yet the program still reads the old value.
import java.lang.reflect.Field;
class Limits {
private final int max = 5;
int getMax() {
return max;
}
}
public class ConstantPitfall {
public static void main(String[] args) throws Exception {
Limits limits = new Limits();
Field f = Limits.class.getDeclaredField("max");
f.setAccessible(true);
f.setInt(limits, 10);
System.out.println(f.getInt(limits));
System.out.println(limits.getMax());
}
}The output is 10 and then 5. The field max is a final field initialized with a compile-time constant, so the compiler replaced max inside getMax() with the literal 5. The reflective write changed the field in memory, but compiled code never reads it. Treat final fields as read-only even though reflection can sometimes write to them. Writing to a static final field fails with IllegalAccessException.
Modules and strong encapsulation
From Java 9, the module system limits setAccessible. Code in one module can reflect on the non-public members of another module only if that module opens the package to the caller. The JDK's own internal packages are encapsulated. In Java 11 you still get an "illegal reflective access" warning for some old libraries, but this fallback was removed in Java 16 and later, and it should not be relied on. If you meet an InaccessibleObjectException, the correct fixes are:
- Use a public API instead of reflecting into internals.
- If you own the target module, add an
opensdirective to itsmodule-info.java. - As a last resort for third-party code, pass
--add-opens module/package=targeton the command line.
Treat option 3 as a temporary workaround. It makes your application depend on another library's internals.
Security
Reflection on untrusted input is dangerous. If a class name or method name comes from user input, an attacker can choose which class gets loaded or which method runs. Never pass raw request data to Class.forName or getMethod. Check the name against an allow-list first. Also remember that Class.forName runs static initializers, so loading a class can execute code.
Common exceptions
| Exception | Usual cause |
|---|---|
| `NoSuchMethodException` / `NoSuchFieldException` | Wrong name or parameter types, or `getMethod` used for a non-public member (use `getDeclaredMethod`) |
| `IllegalAccessException` | Calling a non-public member without `setAccessible(true)`, or writing a `static final` field |
| `InaccessibleObjectException` | `setAccessible` blocked because the module does not open the package |
| `IllegalArgumentException` | Wrong number or type of arguments, or the object is not an instance of the declaring class |
| `InvocationTargetException` | The invoked method threw an exception. Read it with `getCause()` |
| `ClassNotFoundException` | `Class.forName` could not find the name on the class path |
Catch the specific exceptions you can handle. Do not wrap everything in catch (Exception e) and print it, because that hides the real cause.
Design guidance
The right question is whether the structure of the code really is unknown until run time. The diagram shows one way to decide.
Some practical rules follow from it:
- Prefer an interface when you control both sides. A plugin that implements a known interface needs only
Class.forNameand one cast. Every later call is an ordinary, checked, fast call. - Confine reflection to one place. Put it in a small utility class or framework layer, so a rename affects one file and you can test it in isolation.
- Fail early. Resolve and validate all reflective members at startup, such as when you scan annotated classes. A missing field then fails when the application starts, not hours later.
- Write tests for reflective code. The compiler will not catch mistakes in it. A test that exercises every reflective path is the replacement for the missing compile-time check.
- Consider build-time generation. If a framework only needs to read annotations and generate boilerplate, an annotation processor does this work at compile time and leaves no reflection cost at run time. The next chapter covers it.
Exercise
A class has private final int size = 3; and a method int size() { return size; }. Your code sets the field to 8 with setAccessible(true) and setInt, and field.getInt(obj) returns 8, yet obj.size() still returns 3. Why does this happen, and what should you do about it?
Show answer
Because size is a final field initialized with a compile-time constant, the compiler inlined the literal 3 into size(). The write changed the field in memory, but size() never reads it. Do not write to final fields. Redesign the class so the value is not a constant (for example, set it in the constructor), or provide a normal setter.
Exercise
A service calls type.getMethod(name).invoke(target) for every incoming request. Name two changes that reduce its cost, and one change that improves its safety.
Show answer
To reduce cost, cache the Method object (for example in a ConcurrentHashMap) so the lookup runs once, and call setAccessible(true) once when caching. For hot paths, you can also use a MethodHandle stored in a static final field. To improve safety, check the method name against an allow-list before looking it up, so request data cannot select arbitrary methods.