Java Reflection Guide From Basics to When Not to Use It
A complete guide to Java reflection: inspect and invoke classes, proxies, method handles, modules, performance, native image limits and when not to use it.

Frameworks seem to know everything about your code. Spring finds your @Service classes without being told they exist. Jackson fills your record from JSON without a line of mapping code. JUnit discovers methods named nothing in particular and runs the ones annotated @Test. None of that is magic and none of it is generated by a compiler plugin: it is reflection, the part of Java that lets a running program look at its own classes, ask what they contain and use them. Learning reflection makes the frameworks understandable, and makes their error messages readable. It also teaches when not to write it, because reflection costs you things Java is otherwise good at: compile time checking, fast calls and a clear picture of who depends on what.
This guide builds from the first Class object to a small dependency injection container and an object mapper, covering what each step costs. Every section has code you can run on JDK 25. The reading order is the order of power: inspect, read and write, invoke, create, proxy, then the modern alternatives, then the limits. The core idea fits in one sentence worth keeping: reflection turns names, as strings, into behaviour, and every problem with it comes from the fact that the compiler cannot check a string.
If you want to attach your own metadata to classes, the companion post is writing a custom annotation in Java, and for the generics half of the story, type erasure and what it breaks explains why some information is not available even to reflection.
The three ways to get a Class
Everything starts with a java.lang.Class object, the run time representation of a type. There are three ordinary ways to obtain one:
package dev.javahacks.reflect;
public class GetClass {
public static void main(String[] args) throws Exception {
Class<?> byLiteral = String.class; // compile time known
Class<?> byInstance = "hello".getClass(); // from an object
Class<?> byName = Class.forName("java.util.ArrayList"); // from a string, at run time
System.out.println(byLiteral.getName()); // java.lang.String
System.out.println(byInstance == byLiteral); // true: one Class object per type per loader
System.out.println(byName.getSimpleName()); // ArrayList
Class<?> missing = Class.forName("com.example.DoesNotExist");
}
}java.lang.String
true
ArrayList
Exception in thread "main" java.lang.ClassNotFoundException: com.example.DoesNotExistThe literal form, String.class, is checked by the compiler and is what you use when you know the type. getClass() gives the runtime type of an object, which may be a subclass of the declared type. Class.forName is the dynamic one: the name is a string, so a typo is a run time ClassNotFoundException and a class that is on the classpath but initialises badly gives ExceptionInInitializerError or NoClassDefFoundError instead. Keep these two straight: ClassNotFoundException means "looked and it was absent", while NoClassDefFoundError means "present at compile time and missing now", covered in fixing ClassNotFoundException and NoClassDefFoundError.
A Class object is per class loader. The same class loaded by two loaders gives two distinct Class objects that are not equal, and a cast between them fails with ClassCastException: class X cannot be cast to class X, a confusing message seen with application servers and plugin systems.
Inspecting a class
From a Class you can ask for its members. The getDeclared... methods return what the class itself declares, including private members, while the plain get... methods return public members including inherited ones. That difference is the most common source of "why is the method not found":
package dev.javahacks.reflect;
import java.lang.reflect.*;
import java.math.BigDecimal;
import java.util.Arrays;
public class Inspect {
public static class Invoice {
public static final String CURRENCY = "USD";
private final long id;
private BigDecimal total;
protected String note;
public Invoice(long id, BigDecimal total) {
this.id = id;
this.total = total;
}
public BigDecimal total() { return total; }
private void applyDiscount(int percent) {
total = total.multiply(BigDecimal.valueOf(100 - percent)).movePointLeft(2);
}
}
public static void main(String[] args) {
Class<?> type = Invoice.class;
System.out.println("class: " + Modifier.toString(type.getModifiers()) + " " + type.getName());
for (Field f : type.getDeclaredFields()) {
System.out.printf("field %s %s %s%n", Modifier.toString(f.getModifiers()), f.getType().getSimpleName(), f.getName());
}
for (Constructor<?> c : type.getDeclaredConstructors()) {
System.out.println("ctor " + c);
}
for (Method m : type.getDeclaredMethods()) {
System.out.printf("method %s %s(%s)%n", Modifier.toString(m.getModifiers()), m.getName(),
Arrays.stream(m.getParameterTypes()).map(Class::getSimpleName).toList());
}
}
}class: public static dev.javahacks.reflect.Inspect$Invoice
field public static final String CURRENCY
field private final long id
field private BigDecimal total
field protected String note
ctor public dev.javahacks.reflect.Inspect$Invoice(long,java.math.BigDecimal)
method public BigDecimal total()
method private void applyDiscount([int])Note the binary name Inspect$Invoice for a nested class, a detail that shows up in stack traces and in Class.forName strings. The Modifier class decodes the integer bit flags. The order of getDeclaredFields and getDeclaredMethods is not guaranteed by the specification: the JVM currently returns declaration order for fields, but code that depends on it breaks on another implementation. If order matters, sort by name or by an annotation value you control.
Other things you can read from the Class: getSuperclass(), getInterfaces(), isInterface(), isRecord(), isEnum(), isSealed(), getPermittedSubclasses(), getEnclosingClass(), and getModule(). The newer language features are all visible here, a point we return to with records.
Reading and writing fields, including private ones
A Field object reads and writes the value on an instance. The surprise for newcomers is that private fields are reachable, once you ask for permission with setAccessible(true):
package dev.javahacks.reflect;
import java.lang.reflect.Field;
import java.math.BigDecimal;
public class FieldAccess {
public static void main(String[] args) throws Exception {
var invoice = new Inspect.Invoice(7L, new BigDecimal("100.00"));
Field total = Inspect.Invoice.class.getDeclaredField("total");
total.setAccessible(true); // bypass the private modifier
System.out.println("before: " + total.get(invoice));
total.set(invoice, new BigDecimal("80.00"));
System.out.println("after: " + invoice.total());
Field id = Inspect.Invoice.class.getDeclaredField("id");
id.setAccessible(true);
System.out.println("id: " + id.getLong(invoice)); // primitive accessor avoids boxing
}
}before: 100.00
after: 80.00
id: 7That is how Hibernate sets entity fields and how Jackson can populate an object with no setters. There are three failure modes to know.
NoSuchFieldException means the name is wrong or the field is declared in a superclass, because getDeclaredField does not search upwards. Walk getSuperclass() yourself if you need inherited fields.
IllegalAccessException means you forgot setAccessible(true) on a non-public member.
InaccessibleObjectException is the modern one, and it appears when you try to open something inside a module that does not allow it, which is most of the JDK itself:
Field value = String.class.getDeclaredField("value");
value.setAccessible(true);Exception in thread "main" java.lang.reflect.InaccessibleObjectException:
Unable to make field private final byte[] java.lang.String.value accessible:
module java.base does not "opens java.lang" to unnamed module @3b95a09cSince Java 9, modules enforce strong encapsulation: a package is reachable by reflection only if its module opens it. Code in your own application is on the classpath, in the unnamed module, and open to itself, so the example above with Invoice works. The JDK's internals are closed, and since JDK 17 the old escape flag --illegal-access is gone. You can still grant access explicitly on the command line, --add-opens java.base/java.lang=ALL-UNNAMED, which is what you will see in the startup scripts of older frameworks. Treat each such flag as technical debt: it is a statement that a library depends on JDK internals.
What about final fields? Field.set on a final instance field works after setAccessible(true) for ordinary classes, though it is a bad idea: the JIT may have inlined the old value, and the behaviour is formally undefined. It does not work on static final fields or on record and hidden class fields. The platform is moving to make final mean final, with warnings first, under JEP 500; do not build on it.
Invoking methods
A Method can be called on an instance with invoke. The first argument is the target (or null for static methods), followed by the arguments:
package dev.javahacks.reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
public class MethodInvoke {
public static void main(String[] args) throws Exception {
var invoice = new Inspect.Invoice(7L, new BigDecimal("100.00"));
Method discount = Inspect.Invoice.class.getDeclaredMethod("applyDiscount", int.class);
discount.setAccessible(true);
discount.invoke(invoice, 20); // boxes 20 to Integer, unboxes inside
System.out.println(invoice.total()); // 80.0000
Method parse = Integer.class.getMethod("parseInt", String.class);
Object result = parse.invoke(null, "42"); // static: no target
System.out.println(result); // 42
try {
parse.invoke(null, "forty-two");
} catch (InvocationTargetException e) {
System.out.println("method threw: " + e.getCause());
}
}
}80.0000
42
method threw: java.lang.NumberFormatException: For input string: "forty-two"Three details trip people up. First, the parameter types are part of the lookup: getDeclaredMethod("applyDiscount", int.class) finds the method taking a primitive int, while Integer.class would throw NoSuchMethodException. Second, an exception thrown by the invoked method is wrapped in InvocationTargetException; the real cause is e.getCause(). A framework that fails to unwrap it reports "InvocationTargetException" in the log, which tells you nothing, and the actual error is in the nested "Caused by". Third, arguments and results are boxed, Object all the way, and a wrong argument count or type produces IllegalArgumentException: wrong number of arguments or argument type mismatch at run time.
Always unwrap in your own code:
static Object call(Method m, Object target, Object... args) throws Throwable {
try {
return m.invoke(target, args);
} catch (InvocationTargetException e) {
throw e.getCause(); // rethrow the real failure, not the wrapper
}
}Creating instances
For a no-argument constructor, getDeclaredConstructor().newInstance(); for others, pass the parameter types and then the arguments. The older Class.newInstance() is deprecated because it propagated checked exceptions without declaring them:
package dev.javahacks.reflect;
import java.lang.reflect.Constructor;
import java.math.BigDecimal;
public class Create {
public static <T> T create(Class<T> type, Class<?>[] types, Object... args) throws ReflectiveOperationException {
Constructor<T> ctor = type.getDeclaredConstructor(types);
ctor.setAccessible(true);
return ctor.newInstance(args);
}
public static void main(String[] args) throws Exception {
Inspect.Invoice invoice = create(Inspect.Invoice.class,
new Class<?>[]{long.class, BigDecimal.class}, 9L, new BigDecimal("55.00"));
System.out.println(invoice.total()); // 55.00
// plugin style: the class name comes from configuration
String implementation = "java.util.ArrayDeque";
Object queue = Class.forName(implementation).getDeclaredConstructor().newInstance();
System.out.println(queue.getClass().getSimpleName());
}
}ReflectiveOperationException is the common parent of ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException and InvocationTargetException, so one catch covers the family. The plugin style in the last lines is the classic use: a configuration file names a class, and the program instantiates it. For that case, the JDK has a better tool than hand-written forName, ServiceLoader, which finds implementations declared in META-INF/services or a module descriptor and instantiates them for you, with type safety and no strings in code:
for (PaymentPlugin plugin : ServiceLoader.load(PaymentPlugin.class)) {
registry.register(plugin);
}Use ServiceLoader for plugin discovery and reserve Class.forName for the cases where the name truly comes from outside.
Records, enums and sealed types
Modern Java features have reflective support, and a mapper written today should use it. A record exposes its components in declaration order, which is exactly what a serializer needs:
package dev.javahacks.reflect;
import java.lang.reflect.RecordComponent;
import java.util.LinkedHashMap;
import java.util.Map;
public class RecordToMap {
record Customer(long id, String name, boolean active) {}
public static Map<String, Object> toMap(Record record) throws ReflectiveOperationException {
Map<String, Object> out = new LinkedHashMap<>();
for (RecordComponent c : record.getClass().getRecordComponents()) {
out.put(c.getName(), c.getAccessor().invoke(record)); // call the accessor, not the field
}
return out;
}
public static <T extends Record> T fromMap(Class<T> type, Map<String, Object> values) throws ReflectiveOperationException {
RecordComponent[] components = type.getRecordComponents();
Class<?>[] types = new Class<?>[components.length];
Object[] args = new Object[components.length];
for (int i = 0; i < components.length; i++) {
types[i] = components[i].getType();
args[i] = values.get(components[i].getName());
}
return type.getDeclaredConstructor(types).newInstance(args); // canonical constructor
}
public static void main(String[] args) throws Exception {
var map = toMap(new Customer(1L, "Ana", true));
System.out.println(map);
System.out.println(fromMap(Customer.class, map));
}
}{id=1, name=Ana, active=true}
Customer[id=1, name=Ana, active=true]Going through the accessor and the canonical constructor respects the record's own validation, which writing to its fields would bypass. Enums offer getEnumConstants(), and a sealed interface lists its subtypes with getPermittedSubclasses(), which lets a serializer or a visitor generator find every case at run time, a capability that did not exist for open class hierarchies.
Dynamic proxies
A dynamic proxy is an object created at run time that implements one or more interfaces and sends every call to an InvocationHandler. It is the foundation of declarative features: transactions, caching, retries, security checks and mock libraries all wrap a real object in a proxy that adds behaviour around each call.
package dev.javahacks.reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
public class TimingProxy {
public interface Calculator {
int slowAdd(int a, int b);
}
@SuppressWarnings("unchecked")
public static <T> T timed(Class<T> iface, T target) {
return (T) Proxy.newProxyInstance(
iface.getClassLoader(),
new Class<?>[]{iface},
(proxy, method, args) -> {
long start = System.nanoTime();
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
throw e.getCause();
} finally {
System.out.printf("%s took %d us%n", method.getName(), (System.nanoTime() - start) / 1_000);
}
});
}
public static void main(String[] args) {
Calculator real = (a, b) -> {
try { Thread.sleep(20); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
return a + b;
};
Calculator calc = timed(Calculator.class, real);
System.out.println(calc.slowAdd(2, 3));
}
}slowAdd took 20431 us
5The microsecond figure will differ on your machine. The pattern is the point: the caller sees a Calculator, the handler sees every call with the Method and its arguments, and the real object is untouched. Two limits matter. The JDK proxy works only for interfaces. Spring and others use CGLIB or ByteBuddy to subclass concrete classes, with the extra rule that the class and the methods cannot be final, which is why @Transactional on a final method silently does nothing. And self invocation bypasses the proxy: when a method of the target calls another of its own methods, it does so on this, the real object, not on the proxy, so the added behaviour does not run. The second point causes a steady stream of "why is this @Transactional method not transactional" questions; the full treatment is in Spring AOP proxies and how they intercept calls.
A small dependency injection container
Putting annotations and reflection together shows how a framework works. This container reads an @Inject annotation on a constructor, creates the dependencies first and caches singletons:
package dev.javahacks.reflect;
import java.lang.annotation.*;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
public class MiniContainer {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.CONSTRUCTOR)
public @interface Inject {}
private final Map<Class<?>, Object> singletons = new HashMap<>();
private final Map<Class<?>, Class<?>> bindings = new HashMap<>();
public <T> void bind(Class<T> type, Class<? extends T> implementation) {
bindings.put(type, implementation);
}
@SuppressWarnings("unchecked")
public <T> T get(Class<T> type) {
Object existing = singletons.get(type);
if (existing != null) {
return (T) existing;
}
Class<?> concrete = bindings.getOrDefault(type, type);
try {
Constructor<?> ctor = injectConstructor(concrete);
Class<?>[] params = ctor.getParameterTypes();
Object[] args = new Object[params.length];
for (int i = 0; i < params.length; i++) {
args[i] = get(params[i]); // recursion resolves the graph
}
Object instance = ctor.newInstance(args);
singletons.put(type, instance);
return (T) instance;
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("cannot create " + type.getName(), e);
}
}
private Constructor<?> injectConstructor(Class<?> type) throws NoSuchMethodException {
for (Constructor<?> c : type.getDeclaredConstructors()) {
if (c.isAnnotationPresent(Inject.class)) {
return c;
}
}
return type.getDeclaredConstructor(); // fall back to the no-argument constructor
}
}interface Clock2 { long now(); }
class SystemClock2 implements Clock2 { public long now() { return System.currentTimeMillis(); } }
class Billing {
private final Clock2 clock;
@MiniContainer.Inject Billing(Clock2 clock) { this.clock = clock; }
String stamp() { return "billed at " + clock.now(); }
}
var container = new MiniContainer();
container.bind(Clock2.class, SystemClock2.class);
System.out.println(container.get(Billing.class).stamp());Under fifty lines, and it demonstrates everything that makes Spring work: finding the constructor by annotation, reading its parameter types, recursively creating those, caching. What it lacks shows why the real thing is bigger: cycle detection (two classes needing each other would recurse until StackOverflowError), scopes, @Qualifier, lifecycle callbacks and proxies. The point is that the framework is a program, not a mystery, and a missing bean error is a lookup that failed. A look at the real mechanism is in how the Spring container really works.
Method handles: the modern alternative
java.lang.invoke.MethodHandle, added in Java 7, is a typed reference to a method that the JIT can optimise like a direct call when the handle is held in a constant. It does its access check once, at lookup, not at every call, and it has a clean model for security: you can only look up what the Lookup object you hold has access to.
package dev.javahacks.reflect;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public class Handles {
private static final MethodHandle UPPER;
static {
try {
UPPER = MethodHandles.lookup()
.findVirtual(String.class, "toUpperCase", MethodType.methodType(String.class));
} catch (ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
}
}
public static void main(String[] args) throws Throwable {
String result = (String) UPPER.invokeExact("hello"); // exact signature, no boxing
System.out.println(result); // HELLO
MethodHandle bound = UPPER.bindTo("bound value");
System.out.println((String) bound.invoke()); // BOUND VALUE
}
}invokeExact requires the call site's static types to match the handle's type exactly, here (String)String, and fails with WrongMethodTypeException otherwise; invoke adapts the types at some cost. Handles can be composed, with bindTo, filterArguments, guardWithTest, which is how lambdas and string concatenation are linked on modern JVMs. Prefer a handle in a static final field: the JIT treats the handle as a constant only then. VarHandle is the equivalent for fields and arrays with atomic and memory ordering operations, replacing Unsafe for most uses. For application code the practical rule is: if you call the same reflective member many times, use a handle; for a one off call, plain reflection is fine.
Class loaders: why a Class is more than a name
The three ways of getting a Class hide a concept that explains many odd errors: a class is identified by its name together with the class loader that defined it. The JVM has a hierarchy of loaders. The bootstrap loader loads the core java.base module, the platform loader loads the other JDK modules and the application loader loads your classpath. Application servers and plugin systems add loaders of their own so that each deployed application has its own isolated copy of a library.
package dev.javahacks.reflect;
public class Loaders {
public static void main(String[] args) {
System.out.println(String.class.getClassLoader()); // null: the bootstrap loader
System.out.println(java.sql.Connection.class.getClassLoader()); // platform loader
System.out.println(Loaders.class.getClassLoader()); // the application loader
ClassLoader loader = Loaders.class.getClassLoader();
while (loader != null) {
System.out.println("parent chain: " + loader.getName());
loader = loader.getParent();
}
}
}null
jdk.internal.loader.ClassLoaders$PlatformClassLoader@5ca881b5
jdk.internal.loader.ClassLoaders$AppClassLoader@2c13da15
parent chain: app
parent chain: platformThe null for String is not a bug: the bootstrap loader has no Java object to print. Loading is delegated upwards: a loader asks its parent first and only defines the class itself if the parents cannot, which is why you cannot replace java.lang.String by putting your own copy on the classpath. The consequences for reflection are practical. Class.forName("x.Y") uses the loader of the calling class, which can miss classes visible only to another loader, and the fix in frameworks is to use the thread context class loader, Thread.currentThread().getContextClassLoader(), which a container sets to the loader of the application being served. Two copies of the same class in two loaders are different types, so passing an object across the boundary gives ClassCastException: class dev.javahacks.Order cannot be cast to class dev.javahacks.Order (dev.javahacks.Order is in unnamed module of loader 'app'; dev.javahacks.Order is in unnamed module of loader org.apache.catalina.loader.ParallelWebappClassLoader). The message names both loaders, and reading them is the whole diagnosis: the class exists twice, so one of the two copies must be removed from the deployment.
Reading generic signatures
Section after section above worked with raw Class objects, which erase generics. The reflective API still exposes the declared generic types, as the erasure post explained, through the getGeneric... methods and the java.lang.reflect.Type hierarchy. This is how a mapper learns that a field is a List<Order> and not a bare List:
package dev.javahacks.reflect;
import java.lang.reflect.*;
import java.util.List;
import java.util.Map;
public class GenericSignatures {
static class Catalog {
Map<String, List<Integer>> prices;
List<? extends Number> readings;
<T extends Comparable<T>> T max(List<T> values) { return values.get(0); }
}
static String describe(Type t) {
if (t instanceof Class<?> c) {
return c.getSimpleName();
}
if (t instanceof ParameterizedType p) {
var args = java.util.Arrays.stream(p.getActualTypeArguments()).map(GenericSignatures::describe).toList();
return ((Class<?>) p.getRawType()).getSimpleName() + args;
}
if (t instanceof WildcardType w) {
return "? extends " + java.util.Arrays.stream(w.getUpperBounds()).map(GenericSignatures::describe).toList();
}
if (t instanceof TypeVariable<?> v) {
return "type variable " + v.getName() + " extends " + java.util.Arrays.stream(v.getBounds()).map(GenericSignatures::describe).toList();
}
return t.getTypeName();
}
public static void main(String[] args) throws Exception {
for (Field f : Catalog.class.getDeclaredFields()) {
System.out.println(f.getName() + ": " + describe(f.getGenericType()));
}
Method max = Catalog.class.getDeclaredMethod("max", List.class);
System.out.println("returns " + describe(max.getGenericReturnType()));
}
}prices: Map[String, List[Integer]]
readings: List[? extends [Number]]
returns type variable T extends [Comparable[T]]A Type is a small tree: a Class for a plain type, a ParameterizedType for List<Order>, a WildcardType for ? extends Number, a TypeVariable for T and a GenericArrayType for T[]. Real mappers recurse through exactly this structure. The one thing you cannot read is the type argument of a *local variable* or of a *particular instance*, since neither is part of the class file. That is the case the super type token covers, and it is why new TypeReference<List<Order>>() {} exists in Jackson.
Modules: opening your own packages
On the module path, your own code is not open to reflection by default either. A modular application that Jackson must serialise has to say so in its descriptor:
module dev.javahacks.orders {
requires com.fasterxml.jackson.databind;
requires jakarta.persistence;
exports dev.javahacks.orders.api; // compile time access for everyone
opens dev.javahacks.orders.model to com.fasterxml.jackson.databind, org.hibernate.orm.core;
}The distinction between the two keywords is the point. exports lets other modules compile against public types, while opens lets them use deep reflection on every member, private ones included, at run time. A qualified opens ... to grants the right only to named modules, which is the least privilege version. Forgetting it produces an error that mentions the module by name, the same InaccessibleObjectException as before, this time about your own package. Most Spring Boot applications run on the classpath, where the whole application is in the unnamed module and everything is open, which is why the issue is invisible until the first modularisation.
How the frameworks you use rely on it
It is useful to know which reflective feature each well known library depends on, because their errors then make sense.
| Library | What it does with reflection | What goes wrong |
|---|---|---|
| JUnit | Scans for methods annotated @Test, creates the test class by constructor, invokes lifecycle methods | @Test method not found if it is private or has parameters it cannot resolve |
| Spring | Scans for stereotype annotations, calls constructors with resolved dependencies, wraps beans in proxies | NoSuchBeanDefinitionException, final methods not proxied, self invocation skipping advice |
| Jackson | Reads constructors, record components, getters and annotated fields, writes through setters or fields | InvalidDefinitionException: No suitable constructor when no creator can be found; modules not opened |
| Hibernate | Instantiates entities through a no-argument constructor, reads and writes fields, builds proxies for lazy loading | final entity classes cannot be proxied; missing default constructor |
| Mockito | Creates subclasses or inline mocks of classes at run time and intercepts every call | Cannot mock/spy class ... final class on older versions without the inline mock maker |
The recurring theme in the last column is that each failure is a limit of reflection or proxying stated in the library's own words, which the sections above prepared you to read: a class that is final cannot be subclassed, an inaccessible member needs permission, a constructor must be found by exact parameter types.
Debugging reflective code
Reflective bugs are hard because the stack trace shows framework internals instead of your call. A short routine finds the cause.
Read the *innermost* "Caused by" first, since reflection wraps everything: an InvocationTargetException or a framework wrapper such as BeanInstantiationException carries the real exception as the cause, and the first line of the trace is almost never the one that matters. Then identify which of the table's exceptions you have and work from its row. For NoSuchMethodException, print what the class really declares, with the inspector from earlier, because the usual cause is a signature that differs by a boxed type or by a parameter you forgot. For a missing class, print Thread.currentThread().getContextClassLoader() and the resource URL of the class file with getResource("/dev/javahacks/Order.class"), which shows which jar it came from or that it came from nowhere. And when behaviour is wrong rather than failing, turn the reflective call into a log line that records the class, member and arguments, because the stack trace alone does not tell you which of a hundred reflective calls misbehaved.
static Object invokeLogged(Method m, Object target, Object... args) throws Throwable {
System.out.printf("invoke %s#%s(%s) on %s%n", m.getDeclaringClass().getSimpleName(), m.getName(),
java.util.Arrays.toString(args), target);
return call(m, target, args);
}A tool worth knowing for the performance side is Java Flight Recorder: it records method samples, and a reflective hot spot shows up under jdk.internal.reflect or java.lang.invoke frames, which tells you the cost really is in reflection before you rewrite anything.
What reflection costs
The cost has four parts, and only the first is speed.
Call overhead. A reflective Method.invoke boxes arguments, checks access and dispatches through a handle or accessor, where a direct call is inlined by the JIT. Since Java 18, core reflection is implemented with method handles under the covers, which narrowed the gap, but a direct call is still cheaper and a constant MethodHandle is the closest to it. Do not trust a number from an article for your workload; write a JMH benchmark (how to benchmark correctly with JMH) and compare. A mapper that reflects once per class at startup and caches the Method and Field objects is fast enough for almost everything. Calling getDeclaredMethods() on every request is the mistake, because each call copies the array.
Late failure. A misspelled method name compiles and fails at run time, maybe in production on a rare branch. Add startup checks that resolve every reflective lookup eagerly, so errors appear when the application boots.
Hidden coupling. Renaming a method no longer fails the build when some string elsewhere refers to it, and IDE refactoring tools may not see the reference. Reflection breaks "find usages".
Platform friction. Strong encapsulation, native image and obfuscators all need to be told what reflection touches.
Native image and reflection metadata
A GraalVM native image is built by a closed world analysis: it keeps only code it can prove is reachable. A string passed to Class.forName defeats the analysis, so reflective access to a class must be declared in advance, in a JSON file under META-INF/native-image:
{
"reflection": [
{
"type": "dev.javahacks.orders.Customer",
"allDeclaredConstructors": true,
"allDeclaredFields": true,
"allPublicMethods": true
}
]
}Frameworks cope by generating this metadata at build time: Spring's AOT processing and Quarkus's build steps both replace run time classpath scanning with generated code, which is also why they start faster. If you write a library that uses reflection and want it to work in native image, document the types it needs and ship the metadata. The same problem, in another guise, is why Quarkus and Micronaut avoid reflection by design.
Caching reflective metadata
The performance advice above has a concrete form. Look a class up once, build whatever structure you need and keep it. The cheapest correct design is a small cache keyed by Class, filled lazily and safely shared between threads:
package dev.javahacks.reflect;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ClassValue;
public final class MappingCache {
public record Column(String name, Field field) {}
private static final ClassValue<List<Column>> COLUMNS = new ClassValue<>() {
@Override
protected List<Column> computeValue(Class<?> type) {
List<Column> columns = new ArrayList<>();
for (Field f : type.getDeclaredFields()) {
if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) {
continue;
}
f.setAccessible(true); // done once, not per call
columns.add(new Column(f.getName(), f));
}
return List.copyOf(columns);
}
};
public static List<Column> columnsOf(Class<?> type) {
return COLUMNS.get(type);
}
}ClassValue is the JDK's purpose built per class cache: it computes the value once per class, is thread safe, and, unlike a static Map<Class<?>, ...>, does not keep the class alive after its class loader is discarded, which prevents the class loader leak that a naive static map causes in an application server. That last point is a real production failure: a ConcurrentHashMap<Class<?>, X> held by a library jar loaded in a shared parent loader pins every web application's classes in memory across redeploys, and the symptom is OutOfMemoryError: Metaspace after the fifth deployment.
Building a small annotation driven mapper
Reflection, annotations and the cache combine into the thing most applications use reflection for, mapping an object to named values. This mapper writes any object's annotated fields into a map, which could be a SQL parameter source or a JSON tree. The annotation controls naming and exclusion:
package dev.javahacks.reflect;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Mapped {
String name() default "";
boolean skip() default false;
}package dev.javahacks.reflect;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;
public final class ObjectMapper2 {
public static Map<String, Object> toMap(Object source) {
Map<String, Object> out = new LinkedHashMap<>();
for (MappingCache.Column column : MappingCache.columnsOf(source.getClass())) {
Field field = column.field();
Mapped rule = field.getAnnotation(Mapped.class);
if (rule != null && rule.skip()) {
continue;
}
String key = (rule == null || rule.name().isEmpty()) ? column.name() : rule.name();
try {
out.put(key, field.get(source));
} catch (IllegalAccessException e) {
throw new IllegalStateException("cannot read " + field, e);
}
}
return out;
}
}class Account {
@Mapped(name = "account_id") long id = 7;
String owner = "Ana";
@Mapped(skip = true) String password = "secret";
}
System.out.println(ObjectMapper2.toMap(new Account()));{account_id=7, owner=Ana}Run through the design choices. The cache does the reflective lookup and the setAccessible call once per class. Static fields are skipped because they belong to the type, not the instance. The annotation overrides the name and can exclude a secret. A failure to read turns into an IllegalStateException carrying the field that failed, so the message is useful. A production mapper adds type conversion, nested objects, collections and inheritance, and each of those is another few dozen lines, which is the honest measure of why people use Jackson instead of writing this. The exercise is still valuable: when you have written the simplified version, the configuration options of the real one become obvious.
Gotchas in method lookup
Some behaviours of getMethod and invoke surprise even experienced developers.
Overloads. getMethod("add", Integer.class) and getMethod("add", int.class) find different methods. invoke does not do overload resolution for you: you pick the exact signature, and the runtime does not choose the "closest" match the way the compiler does. A framework that supports overloaded methods must implement its own matching.
Bridge and synthetic methods. The compiler adds bridge methods for generics and covariant returns, so getDeclaredMethods() may list the same logical method twice: once with the specific return type and once with Object. Filter with method.isBridge() and method.isSynthetic() when you scan for annotated methods, or you will register a handler twice.
Varargs. A method declared log(String format, Object... args) takes an Object[] as its last parameter when found reflectively, so you must pass the array yourself: m.invoke(target, "x={}", new Object[]{1}). Passing the values loose gives IllegalArgumentException: wrong number of arguments.
Inherited and interface methods. A method declared on an interface and implemented in a class can be invoked through either Method object. If the implementing class is not public, using the class's own Method fails with IllegalAccessException even for a public method, while the interface's Method works. When invoking public API reflectively, resolve the method on the public type, not the private implementation.
Default methods. An interface default method is found with getMethod on the implementing class and invoked normally, but a dynamic proxy that wants to call a default method of its own interface needs InvocationHandler.invokeDefault, available since Java 16.
**Static members and null.** For a static field or method, the target argument is ignored, and passing a real instance does no harm, which is how code written for instance members tends to survive being pointed at a static one.
Common exceptions, decoded
| Exception | What it means | Usual cause |
|---|---|---|
ClassNotFoundException | forName could not find the class | Typo, missing dependency, wrong class loader |
NoSuchMethodException | No method with that name and parameter types | Boxed vs primitive type, wrong declaring class, inherited method looked up with getDeclared... |
NoSuchFieldException | No such field in this class | Field is in a superclass |
IllegalAccessException | Member not accessible | Missing setAccessible(true), or a non-public class in another package |
InaccessibleObjectException | Module does not open the package | JDK internals; add --add-opens or stop using them |
InvocationTargetException | The invoked method threw | Read getCause() |
IllegalArgumentException: argument type mismatch | Wrong argument for invoke | Passing Integer where long is required |
InstantiationException | Class is abstract or an interface | Instantiating the wrong type |
ExceptionInInitializerError | A static initialiser threw | Look at the nested cause |
Keep this table near a debugging session. Almost all reflective bugs are in the first four rows.
A security note
Reflection is a power tool aimed at your own program, and becomes a weapon when the strings come from outside. Class.forName(request.getParameter("class")) followed by newInstance lets a caller instantiate any class on the classpath, including ones with dangerous constructors. Never use untrusted input as a class or method name. If you must map input to behaviour, use an allow list: a Map<String, Supplier<Handler>> keyed by a short name that you control. This is the same lesson as in Java serialization risks, where the stream names the classes. The SecurityManager, which once restricted reflection, was removed in Java 24, so no run time policy now constrains it within a process; the controls are the module system and your own discipline.
Testing code that uses reflection
Test the contract, not the mechanism. For a mapper, assert on the round trip of a record with several field types, a null, a nested record and a collection. For a container, assert on the graph it builds and on the error for a missing binding and for a cycle. For a proxy, assert that the wrapped call returns the real result, that exceptions are unwrapped and that the cross cutting behaviour ran once per call.
@Test
void proxyUnwrapsTheRealException() {
Calculator failing = (a, b) -> { throw new IllegalStateException("overflow"); };
Calculator proxied = TimingProxy.timed(Calculator.class, failing);
assertThatThrownBy(() -> proxied.slowAdd(1, 2))
.isInstanceOf(IllegalStateException.class)
.hasMessage("overflow");
}Avoid using reflection in tests to reach private members of the class under test. That is a signal the class has a part that deserves its own, testable, package visible shape. Spring's ReflectionTestUtils exists and is useful for injecting a mock into a field of a legacy class, but a constructor is the better seam.
When not to use reflection
Reflection belongs in infrastructure: containers, mappers, test frameworks, serialisation libraries. In application logic it is almost always the wrong tool. A decision table:
| You want to | Reach for | Instead of reflection because |
|---|---|---|
| Choose behaviour by type or key | An interface, a Map<String, Strategy> or an enum with methods | The compiler checks it |
| Call something passed in by the caller | A lambda or functional interface | Zero ceremony and inlinable |
| Find implementations of a service | ServiceLoader | Standard, module aware |
| Generate boilerplate such as builders or mappers | An annotation processor or a build plugin | Fails at compile time, no run time cost |
| Work with a closed set of subtypes | Sealed interfaces and pattern matching | Exhaustiveness checks |
| Call the same member repeatedly and fast | MethodHandle in a static final | Near direct call speed |
| Read your own private state in a test | Package private access or a redesign | Tests stay refactorable |
| Copy fields between objects | A mapper generated at compile time | Faster and refactor safe |
A good sign you have reached for reflection too soon is a growing pile of strings naming members. If you can imagine the same code with an interface and one extra class, write that.
A refactoring: from reflective dispatch to a registry
The most common misuse of reflection in application code is dispatching by name. A report generator receives a string such as "sales" from a request and finds the method to run by building its name:
public String generate(String kind) throws Exception {
Method m = ReportService.class.getDeclaredMethod("generate" + capitalize(kind));
return (String) m.invoke(this);
}It works, and every property listed earlier goes wrong at once. A request with kind=admin reaches generateAdmin, a method nobody meant to expose, because the string chooses the method. A rename of generateSales compiles and fails in production. The call cannot be found by "find usages", and every call pays reflective overhead. The cure takes one interface and one map, and it does what the reflective version did, only checked:
public interface Report {
String generate();
}
@Component
public class ReportRegistry {
private final Map<String, Report> reports;
public ReportRegistry(Map<String, Report> reportBeans) { // Spring injects bean name -> bean
this.reports = Map.copyOf(reportBeans);
}
public String generate(String kind) {
Report report = reports.get(kind);
if (report == null) {
throw new IllegalArgumentException("unknown report: " + kind);
}
return report.generate();
}
}Each report is a small class annotated as a component, and the registry holds only what was registered, which is the allow list the security section recommended. The unknown key is a clear, immediate error. Adding a report means adding a class and nothing else, and the compiler verifies that every report implements generate. The conversion also shows when a framework's own reflection is the right tool: Spring uses reflection once, at startup, to find the beans and populate the map, and your code then runs on plain method calls. That division, reflection in the infrastructure and ordinary Java in the logic, is the arrangement to aim for.
A short checklist
Before writing reflective code, run through this list.
- Can an interface, lambda, enum or sealed type express this? If yes, stop.
- Are the names coming from trusted input? If not, use an allow list.
- Are lookups done once and cached?
MethodandFieldobjects are reusable. - Is the failure path unwrapped, with
InvocationTargetExceptionreplaced by its cause and a message naming the class and member? - Does startup resolve every reflective reference, so mistakes show at boot?
- Does the code need
--add-opens? If so, document the flag and the reason, and plan to remove it. - Does it need to run as a native image? Then provide metadata or generate code instead.
- Is there a test for the contract and one for each failure mode in the table above?
Where to go next
Reflection is the entry point to a family of related techniques, and the order in which they pay off is worth knowing. Start with annotations, because they let you move configuration out of strings and into the types themselves. Learn dynamic proxies next, since they explain declarative transactions, caching and retries in Spring, and the self invocation trap that goes with them. Method handles and VarHandle come after, when a measured hot spot justifies them. Annotation processors and build time code generation are the destination for anything performance or native image sensitive, because they do the reflective work once, at compile time, and leave plain code behind. Reading the source of a small library that uses these, such as a mapper or a test framework, is the quickest education, because the problems described above, unwrapping exceptions, caching lookups, handling bridge methods, appear in every one of them in the same form.
A closing rule of thumb
If you cannot explain in one sentence why this code must discover its types at run time, it probably should not. Reflection that serves a framework, a plugin boundary or a serialiser is doing the job it was made for. Reflection that dispatches on a string inside business logic is a design shortcut, and a registry or an interface will serve better.
When this does not apply
Not every program needs to know about reflection to be written well. A typical business application uses it indirectly, through frameworks, and writing it directly is a sign of building infrastructure. If you only need to read a few configuration values into a class, a framework's binding does it better than a hand rolled version. If your target is native image or a latency critical hot path, prefer generated code and method handles. For the primary sources, the [java.lang.reflect package documentation](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/reflect/package-summary.html), the [java.lang.invoke package overview](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/invoke/package-summary.html), JEP 396 and 403 on strong encapsulation of JDK internals and the GraalVM reachability metadata reference are the documents to read.


