Lesson · Reflection, Proxies & Method Handles
Reflection Basics
12 min readReflection Basics
Reflection hands you the Class object a running program already has, lets you read its member tables, and lets you start a call by hand. The compiler typed nothing at the call site, so every check happens at run time instead.
The Class object, the handle you can hold
A running program knows far more than the source code admits: which class an object really is, which members it declares, what each constructor needs. Reflection exposes that knowledge as ordinary objects, and every path through it starts from one of them, java.lang.Class.
Three ways to get a Class object, and they are not interchangeable. A class literal (Handler.class) is resolved at compile time, so renaming the class breaks the build instead of the run. handler.getClass() answers with the runtime class of an instance, which is what the object actually is, not what the variable declares. Class.forName("com.acme.Handler") is the string form, the only one that can throw ClassNotFoundException; the Class Loading lesson owns what happens between that string and a loaded class, and this lesson starts at the point where you already hold the Class object.
What you hold is metadata. One Class object exists per class per loader, shared by everyone who asks, and reading it does not initialize anything, allocate anything or touch static state.
- A class literal is the checked route: the compiler resolves it, so a rename is a build failure rather than a run-time surprise.
- `getClass()` answers from the object itself, so a
Base reference = new Child()gives youChild.class. It is also how code discovers types that generics erased. - `Class.forName(name)` exists for names that only appear in configuration or input; wrap it, because a typo is
ClassNotFoundExceptionat the moment you call it.
Metadata you can hold, not magic. By the time you have a Class object the class is loaded, and every choice after that (look up, check, call) is the same choice the JVM makes for compiled code, written out by hand.
Reading the member tables: declared versus inherited
A Class object is a directory. Each member kind has two listings, and the difference between them is the difference between two questions: what does this class declare, and what can a caller see through it?
The declared family answers with everything the class itself declares, at every visibility, and nothing inherited. The public family answers with the public surface, inherited members included. There is no middle option: if you want protected or package-private members, start from the declared list and filter with getModifiers().
| Question | Methods | What you get |
|---|---|---|
| What does this class declare? | getDeclaredMethods(), getDeclaredFields(), getDeclaredConstructors() | every visibility, no inherited members, may include compiler-generated bridges and synthetics |
| What can a caller see? | getMethods(), getFields(), getConstructors() | public only, inherited included; on an interface, no Object methods are added |
| How do I find one member? | getDeclaredMethod(name, types), getDeclaredField(name) | exact match on the name plus parameter Class objects, or NoSuchFieldException / NoSuchMethodException |
| What about the inherited search? | getMethod(name, types), getField(name) | searches the class and its supertypes, finds inherited public members, never finds a private one |
| Where are the constructors? | declared variants versus the public ones | declared returns every constructor, the public variant only the public ones |
- Order is not specified. The javadoc says the returned arrays are not sorted and carry no order, so anything that indexes into them is already broken.
- Synthetic members appear in declared listings. A covariant override produces a bridge method;
isBridge()andisSynthetic()are how you filter compiler artefacts out. - Interfaces are special in the public listing:
getMethods()on an interface does not add the implicit Object methods, so an empty interface reports zero methods even though its instances answertoString.
Declared for truth, public for callers. Reflection checks at the call, the compiler checked nothing here, so pick the listing by the question you are actually asking.
Invoking: Field.get and set, Method.invoke, Constructor.newInstance
Reading members is the harmless half. Invoking is the half that runs code, through three doors: Field.get and Field.set, Method.invoke, and Constructor.newInstance.
Method.invoke takes the receiver first, then the arguments as varargs, so one source call becomes one reflective call with every primitive boxed: handle.invoke(handler, "42") wraps the string into an Object[] before anything runs. Inside the target the code is ordinary, with real primitives, and the return value is boxed on the way out, void included (it arrives as null).
Dispatch follows the ordinary rule. An instance method is invoked with dynamic method lookup, so the override for the receiver's runtime class runs, exactly as JLS 15.12.4.4 describes for a compiled call. Before any of that, reflection performs the access check the compiler would have performed, now against the member's visibility plus the caller's class, package and module.
- The argument list must match exactly. A wrong count, or a wrapper that cannot be unboxed to the primitive parameter, throws
IllegalArgumentExceptionbefore the target runs. - Primitives box both ways.
intin,Integerout; a primitive array stays a primitive array;voidcomes back asnull. - Field access widens, never narrows.
Field.getIntreads an int or anything wider that fits by conversion; a narrowing conversion is anIllegalArgumentException. - Constructors have their own object.
Constructor.newInstance(...)is the modern route;Class.newInstance()was deprecated in JDK 9 because it propagated the constructor's checked exceptions straight out, bypassing compile-time checking.
A Class object is metadata you can hold; invoke() is dispatch you start by hand. Same virtual dispatch, same access rules, same boxing rules as a compiled call. Only the compiler is missing.
Reflection basics · one call, step by step
Nothing reflective yet. The source holds an ordinary reference, and a direct call here would be compiled, type-checked and inlined like any other call.
source ready · reflective calls: 0
The checked exception parade
Reflection's checked exceptions are the price of a call the compiler could not type. Each one names a different stage: finding the class, finding the member, passing the access check, binding the arguments, or the target itself failing.
| Exception | Stage | What it means |
|---|---|---|
| ClassNotFoundException | loading by name | the string did not resolve to a class; only the string route can produce it |
| NoSuchMethodException / NoSuchFieldException | lookup | no member matches the name and parameter types, so the string in the code is already wrong |
| IllegalAccessException | access check | the caller may not use the member, or a write targets a final field that cannot be modified |
| IllegalArgumentException | argument binding | the count differs, an unwrapping conversion failed, or a value does not fit the parameter |
| InvocationTargetException | the target | the method ran and threw; the real exception is in getCause(), with its own stack trace |
| ExceptionInInitializerError | class initialization | a static initializer failed while the class was being initialized for this access |
| InaccessibleObjectException | setAccessible | the module system refused to open the package; the encapsulation lesson takes that up in full |
The stage is in the type. If you cannot tell which stage failed, the exception type already told you. What it never tells you is the target's own failure, which is always one getCause() deeper.
Generic introspection and the erasure wall
Generic types are erased by the time an instance exists, and reflection is where that sentence stops being abstract. A List<String> at run time is a List: the type argument was checked by the compiler and then removed.
What survives is the signature attached to a declaration. A field declared List<String> names keeps its type argument in the class file, so Field.getGenericType() returns a ParameterizedType whose getActualTypeArguments() holds String. The same query against an object gives nothing useful: list.getClass() is ArrayList, and getTypeParameters() on that describes the class's own variable E, not your data.
- `getGenericReturnType()` and `getGenericParameterTypes()` preserve what the declaration wrote, nested parameterizations such as
Map<String, List<Integer>>included. - `ParameterizedType` exposes
getRawType()andgetActualTypeArguments(), and the arguments are themselvesTypevalues, so recurse instead of casting. - `TypeVariable` represents a variable such as
T, not the value it took; its upper bounds come fromgetBounds(). - `WildcardType` and `GenericArrayType` cover
? extends NumberandT[], which erasure turns intoNumberandObject[]at run time. - `instanceof List<String>` does not compile, because the check would need the erased argument; test the raw type and validate the contents instead.
You can inspect the declaration, never the instance. Erasure means the honest answer to a question like type arguments of this list is the declaration's signature or an explicit element check.
The cost, and the cache-the-member pattern
A reflective call is not free, and the price is itemised. There is the member lookup when it is not cached, an access check on every call unless it was suppressed, boxing for each primitive argument and return value, and a call shape the JIT cannot inline the way it inlines an ordinary call. None of that is fatal; all of it matters in a loop.
The standard answer is the cache-the-member pattern: look up the Method, Field or Constructor once, keep it, and reuse it for every call. Serializers, mappers and framework proxies have done exactly this for as long as they have existed.
One version note worth carrying. Since JDK 18 (JEP 416) core reflection is implemented on top of method handles, and that JEP's own benchmarks show the new implementation significantly faster when the member object lives in a static final field, because the JIT can constant-fold it, and slower when it does not, especially for field access. Caching in a constant is both the tidy pattern and the fast one. For the layer underneath the API, the MethodHandles and VarHandles lesson builds it from MethodHandles.Lookup outward.
Look up once, call many. A member object cached in a static final field is the pattern every framework uses, and since JDK 18 it is also the one the runtime rewards.
Structure · one Class object, three member tables
declared means every visibility, never inherited
obj.getClass() and Handler.class return this same object; Class.forName resolves the class before handing it back.
what one invoke() does, in order
Catch the wrapper, lose the cause
The classic production bug is a catch around a reflective call that logs e.getMessage(). For an InvocationTargetException that prints the wrapper's message, which says nothing about the real failure: the type, the message and the application frames all live inside getCause(). Unwrap before logging, and if you rethrow, rethrow the cause. A wrapper in a log file is a wrapper nobody unwraps.
Interview angles
What is a Class object, and how do you get one?+
The runtime representation of a class or interface: one shared instance per class per loader. You reach it through a class literal, obj.getClass(), or Class.forName(name), and reading it does not initialize the class.
The three entry points differ in what the compiler can check and when loading happens. The literal is resolved at compile time, getClass() reads the object's runtime class, and forName is a run-time request that can fail with ClassNotFoundException.
Common misconception: That a Class object is something you create or copy. The JVM builds it when the class is defined, and every lookup returns that same instance.
getMethods versus getDeclaredMethods?+
getMethods returns the public methods, inherited ones included, and never private or package-private ones. getDeclaredMethods returns everything the class itself declares, at every visibility, and nothing inherited.
Neither listing guarantees order, and declared listings can contain compiler-generated bridge and synthetic methods, which is what isBridge and isSynthetic are for.
Common misconception: That getDeclaredMethods is a superset of getMethods. The declared listing is wider on visibility but always narrower on inheritance, so the two answer different questions.
What does Method.invoke do with the arguments and the return value?+
It takes the receiver, binds the arguments into an Object array with primitives boxed, performs the access check, and dispatches with dynamic method lookup. The target runs with real primitives, and its return value is boxed back, with void arriving as null.
Dynamic lookup means the override on the receiver's runtime class runs, not the version declared on the static type. That is the same rule JLS 15.12.4.4 gives for a compiled call.
Why does reflection wrap the target's exception instead of letting it through?+
The reflective call must distinguish the call failing from the body throwing. So the body's exception arrives inside InvocationTargetException, and the real one is getCause().
Common misconception: That the wrapper is the failure. Logging the InvocationTargetException alone loses the type, the message and the frames of the actual bug.
Follow-up: How would you rethrow it so the caller sees the original?