Lesson · Reflection, Proxies & Method Handles
Where reflection shows up: frameworks, caches and startup
10 min readWhere Reflection Shows Up
Frameworks do not call reflection because it is fast; they call it once, at startup, and then use what they cached. The same shape turns up in Spring, Hibernate, Jackson and JUnit, and it explains the two production questions you are actually asked: why startup is slow, and why a native image fails until reflection is configured.
The pattern: scan once, cache, invoke forever
Every framework you use does the same three things. At startup it scans: it looks at classes, reads their annotations, and decides which of them matter. It then registers what it found, reflecting on the survivors once and storing resolved references in a registry. From then on, each unit of work consults that registry and calls what it points at.
The scan is the expensive part and it is bought once per process. The steady state is a map lookup plus a call, and neither of those is reflective in the way people fear. That is why "reflection is slow" is a half-truth: reflection is slow per call, and a framework mostly does not call it per request. When you measure a startup regression, you are measuring the scan.
| Framework | What it scans | What it caches | What breaks without configuration |
|---|---|---|---|
| Spring | classes on the classpath, read as metadata to decide which are components | bean definitions, the constructor to use, injection points | a scan package is fixed at build time; a native image needs the discovered classes registered |
| Hibernate / JPA | entity classes and their annotations, when the persistence unit starts | the entity metamodel: columns, associations, access strategy, accessors | an entity missing from the mapping, or one without a no-arg constructor, fails at bootstrap |
| Jackson | the target type the first time it is read or written | serialisers and deserialisers per type, with resolved property accessors | a type reached only by its name, with no static reference anywhere, needs a hint in a native image |
| JUnit | test classes on the classpath, then the methods in each | test methods, lifecycle methods, the extension order | classes generated or loaded by name at run time must be registered for a native image |
- Scan: walk the classpath and read metadata to decide which classes matter. The cost scales with how much is on the classpath, not with how much of it you use.
- Register: reflect on the survivors once. Constructors, injection points, mapped properties and annotations all become entries in a registry keyed by type and member.
- Invoke: per request, look up the entry and call it, through a
Method, aConstructor, a generated accessor class or a handle. The expensive checks are already behind you.
Frameworks do not use reflection because it is fast; they use it once because it is thorough. The scan has to see everything and the call has to be cheap, so the design separates those two moments, and almost every framework question you will be asked is a question about which moment you are looking at.
Spring: the scan you can read in the startup log
@Component classes are found by a classpath scan. Spring reads candidate class files through an ASM-based metadata reader for that first decision, precisely so it does not have to load every class on the path just to reject it. The survivors are loaded, and their constructors are reflected on to work out what to inject: one lookup at startup, then a plan for building the bean. After that the container hands out references it already holds.
Cross-cutting behaviour (transactions, caching, security) arrives as a proxy around the bean, which is the dynamic-proxies lesson's territory: an interface-shaped bean gets a JDK dynamic proxy, everything else gets a generated subclass. Either way the per-call cost is a generated class, not a reflective lookup.
- Scan cost scales with the classpath, not with your code. A wide base package over a fat jar reads far more classes than the application uses, and narrowing that package is a startup fix rather than a micro-optimisation.
- Constructor injection is the scan, made visible. The constructor Spring chose at startup is the one it calls for every bean it builds; nothing about it is resolved per request.
- Native images need the scan as build input. Spring Boot 3 on Spring Framework 6 (Java 17 baseline) runs AOT processing at build time and emits reachability hints, reflection configuration included, for the closed-world build.
- Auto-configuration is a scan too. Every starter contributes candidates, so adding a dependency can widen the scan even when you write no new code.
When the startup log shows one slow bean, count the classes first. Most of a slow Spring start is classpath reading and metadata building, and the fix is usually a narrower scan or a smaller classpath, not a faster reflective call.
Hibernate and Jackson: the mapping decides what reflection may do
JPA builds a metamodel of your entities when the persistence unit starts. That metamodel is the cache: columns, associations, the access strategy for each property, and the plan for reading and writing it. Two requirements come from that design rather than from taste. An entity needs a no-arg constructor (it may be protected or package-private, but it must exist, because the provider has to instantiate a class it did not create), and the access strategy follows the placement of @Id: on a field means the provider reads and writes fields directly, on a getter means it uses the property.
Records sit on the other side of that line. A record has no no-arg constructor and no setters, so it maps cleanly as an immutable value type or a query result, and not as an entity.
Jackson resolves accessors per property the first time it meets a type, then caches the serialiser and deserialiser for that type. Public getters and fields are used as they are; records go through the canonical constructor (record support arrived in Jackson 2.12). Constructor parameter names are the one thing the class file does not carry by default, which is why -parameters at compile time (or jackson-module-parameter-names) decides whether @JsonProperty is needed on every component.
- The no-arg constructor is a requirement, not a suggestion. The framework instantiates the object, so it cannot depend on a constructor of yours; a protected one is enough, as long as it exists.
- `@Id` placement is the access strategy. Field access bypasses your setters entirely, which is why adding validation to a setter does nothing for a JPA-loaded entity.
- Cache granularity is the type. Jackson pays for property introspection once per type, not once per value, so a new type in a hot path costs more than more instances of a known one.
- Records move the mapping to the constructor. One place where a framework prefers a canonical constructor over setters, which is also why serialisation libraries had to be taught about them.
The mapping is resolved once, and the annotations are the declaration that makes it possible. Reflection cannot guess your intent, so every framework here trades a little declaration in exchange for a resolved, cached plan.
JUnit: reflection as a test runner
A test run is a scan followed by per-class reflection. JUnit walks the classpath for classes with @Test methods, reflects on each class to order the methods, runs the lifecycle callbacks around each one, and assembles the extension chain. Nothing about that is different in shape from Spring's container: discovery at the start, invocation after.
Two rules fall straight out of it. @BeforeAll must be static unless the class opts into one instance per class with @TestInstance(PER_CLASS), because a static callback does not need an instance to run. And a test class needs a constructor the runner can call: a no-arg one, or one whose extra parameters a parameter resolver can supply.
- Test discovery is the scan, so a build that gets slower as tests accumulate is usually reading more classes, not running slower tests.
- Lifecycle methods are invoked reflectively per test, which is why they may not be private, and why the before-all pair is static by default.
- Display names are metadata.
@DisplayNameis read at discovery time and shows up in reports; it never reaches a compiled call site.
A test runner is a framework that happens to live in your build, and it uses exactly the scan, cache and invoke shape, at test scope, on every run.
The cost model, and the regression you will actually debug
The numbers fit in a sentence: a reflective lookup costs a handful of microseconds and is paid once per process, a cached invocation costs what the underlying call costs, and a startup regression is almost always a scan that got wider. Frameworks cache whatever they resolved, whether that is a Constructor, a Method, a generated accessor class or a handle, and the per-call price afterwards is the call.
So the fix for a slow start is structural: fewer scanned classes, a narrower base package, fewer auto-configurations, a smaller classpath, or lazy initialisation of the parts nobody needs at boot. Making the reflective call itself faster is the classic wrong turn, and the sequence below is how to avoid it.
- Measure the phases, not the total. Startup logs, framework bootstrap messages and a JFR recording tell you whether classpath reading, metadata building or one slow bean is the cost.
- Count what was scanned. A wider base package or a new starter with its own components changes the scan size, and that is the number that moved.
- Check what changed since the last good start. A new dependency is a more common cause than any change in how reflection behaves.
- Only then look at per-call work, and only if the symptom is throughput rather than startup. A reflective call in the request path is worth replacing with a cached handle; a scan is not a per-call problem at all.
- If the application starts many times (containers, serverless), remember the scan is paid per process. Starting fewer, warmer processes changes the total far more than a faster call.
Reflection is a scan-time tax, not a steady-state one. Optimise the scan (fewer classes) or the process count (fewer cold starts), and leave the invoke alone.
Framework boot · what is paid once and what is paid per request
classes read by the scan
0
grows with the classpath, not with the code you wrote
entries in the registry
0
constructed once, then only read
per-request work
none yet
after startup, this is the whole cost
A JVM starts. The classpath is fixed and nothing has been looked at yet; the framework knows where to look, not what is there.
Counts are illustrative: 412 classes on the classpath and 37 surviving components stand in for a small service. The shape is what matters, and it is the same in every container you will read.
Native images and modules: where configuration becomes mandatory
A GraalVM native image is built by closed-world analysis: the builder decides at build time which classes exist in the image, so a name that only appears as a string at run time cannot be seen. Reflection therefore has to be declared, as reachability metadata (reflect-config.json), as hints emitted by the framework's AOT engine, or as the configuration recorded by the tracing agent while the application ran on the JVM (-agentlib:native-image-agent=config-output-dir=...).
Two failures are typical. A class reachable only through reflection is not in the image at all, so its first use fails at run time; or the class is present and one member was never registered. Both are configuration problems rather than code problems, and the packaging-deployment lesson carries the rest of the build story.
Modules supply the other knob. Since Java 9 the module system refuses deep reflection into a package it does not consider open, and everything on the classpath lives in the unnamed module, which is why this bites modular applications and JDK-internal access first. Strong encapsulation of JDK internals became the default in JDK 16 (JEP 396), and JDK 17 removed the --illegal-access escape hatch (JEP 403). What remains is --add-opens, a launch or build flag, and the reflection-encapsulation lesson takes apart what opening a package really costs.
- Reflection configuration is a build input. It is read when the image is built, so a missing entry shows up as a runtime failure in the image, never as a warning in the JVM run that preceded it.
- The tracing agent is how you discover the list. Run the application on the JVM, exercise the paths, and let the agent write down what it reflected on; then keep that file under version control like any other build input.
- Hints are cheaper to maintain than lists. A framework's AOT engine derives what the scan would have found and emits it, which is why a supported stack needs almost no hand-written configuration.
- Annotations are the visible surface of all of this. The framework reads your annotations at scan time to build the cache, and the consuming-annotations lesson covers the reading side in detail.
A closed world cannot see a string. Every reflective name has to become a build-time fact, and that is the whole reason a JVM application that works perfectly can fail in a native image.
Frameworks · one scan, then a cache
the same four boxes turn up in every container
runtime lane
the input: every jar you added, whether or not the application uses a class from it
reads candidate classes as metadata, filters them, then loads the survivors and reflects on them
what the scan resolved: constructors, members, mappings, accessors, all keyed by type
per unit of work: look the entry up, call what it points at, resolve nothing
build-time lane, only when the target is a native image
reflect-config.json, hints emitted by the AOT engine, or the file the tracing agent wrote during a JVM run
the builder decides which classes exist in the image, so a name that only appears at run time cannot be discovered
no scan, because the scan happened as analysis; the cache is whatever the configuration declared
An entry that is missing from that configuration is invisible at build time and fatal at run time, on the first use of the name it should have covered.
The wrong number to optimise
A startup regression sends people to the call: replacing Method.invoke with a handle, adding a cache in front of a lookup that was already cached. It almost never helps, because startup is not spent in calls. It is spent reading class files and building metadata, so the numbers that move are the size of the classpath, the width of the scan and the number of components that survive it. Read the count of classes scanned before you read a single call count; if the symptom is a slow start, the fix is structural, and if the symptom is slow requests, then per-call reflection is worth a look.
Interview angles
Why do frameworks rely on reflection if reflection is slow?+
Because they pay for it once. The scan and the metadata building happen at startup, and the per-request path uses what was cached, which is a map lookup plus a call. The slowness lands on startup, where it is visible and measurable.
That is also why lazy initialisation changes the shape of a start: the scan still happens, it just happens on first use, which can trade a slow boot for a slow first request.
Common misconception: That frameworks inspect your classes on every request. They inspect them once and keep the result.
Why does Hibernate require a no-arg constructor on an entity?+
Because the provider instantiates entities itself, including for rows it materialises without going through your code. A constructor it can call with no arguments, plus field or property access, is the only combination that always works.
The constructor may be protected or package-private, so it does not have to be part of your public API, but it must exist. Records have no such constructor, which is why they map well as value types and poorly as entities.
Follow-up: What decides whether the provider uses fields or setters? The placement of @Id: on the field means field access, on the getter means property access.
A JVM build passes and the native image fails on the same code. Why?+
The image was built by closed-world analysis, so a class that is only referenced by name at run time may not be in the image, or a member of it may never have been registered as reflectively reachable. The JVM could resolve the name at run time; the image cannot.
The fix is reachability metadata: reflect-config.json, hints generated by the framework's AOT engine, or the file the tracing agent records from a JVM run. It belongs in version control next to the build files.
Follow-up: What is the same problem at the module layer? Deep reflection into a package that is not open to your module, with --add-opens as the (blunt) way to open it.
How would you debug a startup regression in a Spring or Hibernate application?+
By measuring the phases rather than the total, then counting what was scanned. Narrowing the base package, removing a starter, or trimming the classpath addresses the real cost; replacing reflective calls does not, because startup is not spent in calls.
The symptom tells you where to look. Slow start points at classpath reading and metadata building, and is size-bound. Slow requests point at per-call work, and that is where a cached handle earns its keep.
Common misconception: That a faster invoke makes a faster startup. It cannot: the startup cost is proportional to how many classes were read, not to how many methods were called.