What is reflection in Java, what do frameworks use it for, and when is it the wrong tool?
answer
- types unknown at compile time
- Class, then Field, Method, Constructor
- scanning for annotations at startup
- speed, safety, encapsulation
- names in strings escape the compiler
basics
~20 sReflection lets Java code inspect classes and use their members at runtime, through Class and java.lang.reflect. Frameworks use it on types they never compiled against. It is the wrong tool when the type is known at compile time.
solid answer
~40 sReflection is runtime access to a loaded class's metadata and members: from a `Class` you get `Field`, `Method` and `Constructor` objects, then read, call or instantiate through them. It exists for code that must work on types it never saw at compile time, such as dependency-injection containers, object mappers, serializers and test runners, which find members by name or annotation. Its main costs are speed, because a call goes through an argument array, boxing and usually an access check; safety, because names and types are checked only at runtime; and encapsulation, because it can reach private members, which modules may refuse. So it is the wrong tool when you know the type at compile time: use an interface, a lambda or a method reference, and measure before keeping it on a hot path.
code
java · 34 linesimport java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MiniRunner {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Check {}
public static class Checks {
@Check public void passes() {}
@Check public void fails() { throw new IllegalStateException("broken"); }
public void notACheck() {}
}
public static void main(String[] args) throws ReflectiveOperationException {
Class<?> type = Class.forName("MiniRunner$Checks");
Object target = type.getDeclaredConstructor().newInstance();
for (Method m : type.getDeclaredMethods()) {
if (!m.isAnnotationPresent(Check.class)) {
continue;
}
try {
m.invoke(target);
System.out.println(m.getName() + ": ok");
} catch (InvocationTargetException e) {
System.out.println(m.getName() + ": " + e.getCause());
}
}
}
}go deeper
Recall the definition: inspecting classes and using their members at runtime, through Class and java.lang.reflect. Name two framework uses, such as dependency injection and test runners, and say that errors move from compile time to runtime.
Explain what a reflective call does beyond a direct one: an argument array, boxing, an access check and wrapped exceptions. Say why a lookup should be kept rather than repeated, and which alternatives fit a known type.
Show the judgment of where it belongs: startup wiring is usually fine, per-item hot loops need measuring, and reaching into another library's private fields breaks on upgrades and under module rules, so you say what you would do instead.
The tradeoff is flexibility against what tools and the runtime can see. A lead decides whether a shared library should expose reflective extension or typed plug-in interfaces, weighing upgrade risk under strong encapsulation against the cost of generated code.
## What reflection is **Reflection** is a program examining and using its own classes while it runs. The `java.lang.reflect` package documentation defines it as programmatic access to information about the fields, methods and constructors of loaded classes, and the use of those reflected objects to operate on their underlying counterparts, within encapsulation and security restrictions. That gives it two halves: - **Inspect:** starting from a `java.lang.Class` object, list a type's fields, methods, constructors, modifiers and annotations. Which members each lookup returns is the declared-versus-public distinction. - **Act:** use what you found, through `Field.get` and `set`, `Method.invoke` and `Constructor.newInstance`. Ordinary code names a type and the compiler checks the call. Reflective code holds a value describing the type, often found from a string or an annotation, and nothing is checked until the line runs. What you see is the compiled class, not the source. The package documentation says core reflection presents a JVM model rather than a language model, so compiler-generated **synthetic** members such as bridge methods can appear in the results, and `getDeclaredMethods()` promises no particular order. ## What frameworks and libraries use it for The common situation is a framework compiled long before the classes it has to work with exist. It cannot name them, so it discovers them: - **Dependency-injection containers** find annotated constructors and fields, create objects and wire them together. - **Object mappers and serializers** walk a class's fields or accessors to turn objects into rows, JSON or XML and back. - **Test runners** find annotated methods, instantiate the class and invoke each one. - **Dynamic proxies** deliver each call to a handler as a `Method` object, which is covered with dynamic proxies. The JDK does it too. The package documentation names Object Serialization and JavaBeans among the services it serves, and `ServiceLoader` obtains a provider by reflectively calling its public static `provider` method or its public no-argument constructor. ## What it costs | Cost | What happens | Example | |---|---|---| | **Speed** | `Method.invoke(Object, Object...)` takes arguments in an array, boxes primitives, and checks access unless `setAccessible(true)` was called | An `int` result comes back as an `Integer` | | **Safety** | Names and signatures are checked at runtime | A misspelled name throws `NoSuchMethodException` | | **Encapsulation** | Code can depend on another class's private members | A module that does not open the package causes `InaccessibleObjectException` | | **Tooling** | A name inside a string is invisible to the compiler and to rename refactorings | A renamed method breaks only when that line runs | A few details matter in practice: - `Method.invoke` wraps anything the target throws in `InvocationTargetException`, so the real failure is at `getCause()`. - In this JDK each lookup returns a fresh copy, which no public page promises. On JDK 25 and 27, two `getMethod` calls give objects that are `equals` but not the same, so look up once and keep the result. - Since JDK 18 (JEP 416) core reflection runs on method handles. The JEP advises holding `Method`, `Constructor` and `Field` objects in `static final` fields so the JIT can constant-fold them. The details of invocation cost and of module access are covered with dynamic invocation and with `setAccessible`. ## When it is the wrong tool Reflection earns its costs when the type really is unknown until runtime. It is usually wrong in these cases: - **The type is known at compile time.** Call it directly or through an interface, and let the compiler check it. - **You are choosing behaviour by name.** A map from names to lambdas or method references keeps the choice dynamic and the calls checked. - **You need plug-ins.** `ServiceLoader` with a service interface does the reflective part for you and hands back typed objects. - **A hot loop calls it per item.** Keep the lookup out of the loop and measure. If the cost shows up, consider a `MethodHandle`, or code generated at build time by an annotation processor. - **You want another library's private state.** That couples you to internals that can change without notice, and modules can refuse it. ## Version notes `Method`, `Field` and `Constructor` date from Java 1.1, and `Method.invoke` has the same body at JDK 25 and 27. One visible difference: since JDK 26 (JEP 500) mutating a `final` field through deep reflection prints a warning by default, and JEP 500 says a future release will deny it. Such code prints the warning on JDK 27, and the same code on JDK 25 prints none.
- If reflection costs speed, why do so many frameworks rely on it?Much of their reflection is one-time work: scanning and wiring at startup, where a slower call hardly matters. On repeated paths they can keep the looked-up objects rather than search again. JEP 416 also ran serialization benchmarks using real-world libraries and found no degradation from a change that slowed some field-access microbenchmarks, a reminder that microbenchmarks and applications differ.
- Why does Java's Method.invoke wrap the target method's exception instead of letting it propagate?`invoke` declares `InvocationTargetException` for anything the underlying method throws, which keeps a failure inside the target separate from a failure of the reflective call itself, such as `IllegalAccessException` or `IllegalArgumentException`. The original is at `getCause()`. Code that logs only the wrapper hides the real error.
- Does Class.getDeclaredMethods() return exactly the methods written in the source file?Not necessarily. Core reflection presents a JVM model, not a language model, so a compiler-generated bridge method can appear, and `Method.isBridge()` and `isSynthetic()` let you filter such methods. The Javadoc also says the array is not sorted and is in no particular order, so a framework that needs an order has to impose one itself.
- Reflection only reads metadata; it cannot call methods or create instances.
- The compiler checks reflective calls, so a misspelled method name fails at build time.
- Reflection is always too slow to use anywhere in production code.
- setAccessible(true) gets past private in every class, whichever module owns it.
- Method.invoke lets the target method's own exception reach the caller unwrapped.
- At JDK 27, getMethod returns one shared object, so looking it up on every call costs nothing.
- java.lang.reflect.Method
- Java 1.1
- java.lang.reflect.Field
- Java 1.1
- java.lang.reflect.Constructor
- Java 1.1
Assumes Java 27; core reflection has run on method handles since Java 18, and mutating a final field reflectively warns since Java 26 but not at Java 25.
context
- java.lang.reflect (Java SE 27 & JDK 27)docs.oracle.com
- Method (Java SE 27 & JDK 27)docs.oracle.com
- Method.java at jdk-27-gagithub.com