Sub topic 15
Performance, safety, and design pitfalls
This chapter assumes you can already look up a Method or Field, call setAccessible(true), unwrap InvocationTargetException, and read the MethodHandle example from the previous chapter. Here you will learn what reflection costs, where it can hurt you, and when to choose something else.
Where the time goes
Reflection is slower than a direct call for three main reasons:
- Lookup.
getMethodandgetDeclaredFieldsearch the class's members. Each call returns a fresh copy of theMethodorFieldobject. - Invocation overhead.
Method.invokeboxes primitive arguments, allocates anObject[], and checks access on each call. - Fewer JIT optimizations. The JIT compiler usually cannot inline a reflective call the way it inlines a direct call.
The most useful habit is to look a member up once and reuse it.
import java.lang.reflect.Method;
public class CachedLookup {
private static final Method LENGTH;
static {
try {
LENGTH = String.class.getMethod("length");
} catch (NoSuchMethodException e) {
throw new ExceptionInInitializerError(e);
}
}
static int length(String s) throws Exception {
return (int) LENGTH.invoke(s);
}
public static void main(String[] args) throws Exception {
System.out.println(length("reflection"));
}
}A MethodHandle stored in a static final field is treated as a constant by the JIT compiler, so it can be inlined. The same handle in an ordinary field gets no such treatment. Measure with a benchmark tool such as JMH before you change a design for speed. Hand-written timing loops are unreliable on the JVM.
Safety problems
Reflection moves checks from compile time to run time.
- Names become strings. If you rename a method,
getMethod("greet", ...)still compiles and then throwsNoSuchMethodExceptionwhen it runs. - Encapsulation is bypassed.
setAccessible(true)lets you reach private state. Code that depends on a library's private fields breaks when the library changes. - Modules push back. Java 11 only warns about illegal reflective access to JDK internals. Newer releases deny it by default with
InaccessibleObjectException. If you must open a package, use--add-opens, and treat it as a temporary fix. - Untrusted names are dangerous. Passing user input to
Class.forNamelets a caller load and initialize any class on the classpath. Check names against an allow-list. - Final fields are unreliable. Writing a
static finalfield may have no effect, because the compiler can inline constant values into other classes.
Design pitfalls
| Pitfall | Symptom | Better approach |
|---|---|---|
| Reflection where an interface would work | Strings and casts everywhere | Define an interface and call it directly |
| Looking up members on every call | Slow hot paths | Cache `Method`, `Field`, or `MethodHandle` |
| Catching `Exception` and ignoring it | Silent failures | Handle each exception type and unwrap `getCause()` |
| Depending on private members | Breaks on library upgrades | Use public APIs |
| Reflection in tools that shrink or compile ahead of time | `ClassNotFoundException` after packaging | Register reflected classes in the tool's configuration |
Reflection fits code that cannot know types in advance, such as frameworks, serializers, and test tools. For application logic, prefer interfaces, lambdas, ServiceLoader, or compile-time annotation processing, which the last chapter covers.
Exercise
A hot loop calls obj.getClass().getMethod("process").invoke(obj) a million times. Name two changes that reduce its cost, and say what safety problem remains afterward.
Show answer
Look up the Method once and store it in a static final field, or use a MethodHandle held in a static final field. Then call the cached object inside the loop. The call is still resolved by the string name "process", so a rename fails only at run time. A test that executes the lookup is needed to catch it.