Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A Spring Boot native image builds successfully but fails at runtime with a ClassNotFoundException from a JSON library used through reflection. How would you diagnose and fix it?

The class the JSON library loads by reflection was never registered, so native-image's static analysis did not see it and left it out of the executable. To diagnose it, we run the application on the JVM with the native-image tracing agent and exercise that code path, which records the reflective accesses as metadata; we also check the GraalVM Reachability Metadata Repository for the library. The lasting fix is to register a hint in code with a RuntimeHintsRegistrar or @RegisterReflectionForBinding, and to run native tests in CI so the next one is caught before production.

Why this question is asked

This is the most common native image failure: the build is green, the service starts in 80 milliseconds, and then a particular request fails with an exception that never happens on the JVM. Interviewers ask it because fixing it well needs an understanding of why the class is missing, not just a pasted config file. In this answer, we will reproduce the failure, see why the class is not in the image, find the missing metadata with the tracing agent and the metadata repository, fix it with Spring's hint APIs, and add a test that keeps it fixed.

1Reproducing the Failure

Imagine an event consumer that receives JSON with a type field and turns it into the matching Java class. The class name comes from the message, so the code loads it by name.

Java
record OrderCreated(String orderId, long amountCents) {}
Object toEvent(String json, String typeName) throws Exception {
Class<?> type = Class.forName("com.example.events." + typeName); // name from the message
return objectMapper.readValue(json, type);
}
// On the JVM:
toEvent("{\"orderId\":\"A1\",\"amountCents\":4200}", "OrderCreated");
// -> OrderCreated[orderId=A1, amountCents=4200]
// In the native image:
// java.lang.ClassNotFoundException: com.example.events.OrderCreated
// at java.lang.Class.forName(...)

Notice that nothing in the code mentions OrderCreated directly. The only link between the call and the class is a string built at run time.

2Why the Class Is Not in the Image

native-image builds the executable from a points-to analysis that starts at main and follows the code. It includes only classes it can prove are reachable: the closed-world assumption. A call like Class.forName("com.example.events." + typeName) has a name that is unknown until run time, so the analysis cannot tell which class it means, and OrderCreated, used nowhere else, is never reached. It is not in the executable, and no class can be loaded later, hence ClassNotFoundException.

Even when a class is reachable, Jackson needs more: it reflects over the record's constructor, accessors and fields to bind JSON. Without reflection metadata for those members, a similar failure appears as an exception about missing constructors or no properties found. So the fix must register the type for reflection with its members, not only make it reachable.

Same code, two runtimes
StepOn the JVMIn the native image
Class.forName("...OrderCreated")loads class from the jarclass not in image -> exception
Jackson reads constructorreflection always worksneeds registered constructor
Jackson reads accessorsreflection always worksneeds registered methods
On the JVM everything in the jar is available; in a native image only what was registered or reached.

3Finding the Missing Metadata

The tracing agent is a Java agent shipped with GraalVM. We run the normal jar on the JVM with -agentlib:native-image-agent and exercise the failing path, for example by sending the event through a test or a local request. The agent watches every reflective call, proxy, resource load and serialization and writes the metadata native-image needs. We then read what it recorded, which tells us exactly which classes and members were used, and copy the relevant entries into the project. The file layout differs between GraalVM versions (older versions write reflect-config.json and friends, newer ones a single reachability-metadata.json), so check your version.

Shell
$ java -agentlib:native-image-agent=config-output-dir=/tmp/agent-out -jar target/orders.jar
# ... send one OrderCreated message, then stop the app
$ grep -A6 OrderCreated /tmp/agent-out/reachability-metadata.json
"type": "com.example.events.OrderCreated",
"allDeclaredFields": true,
"methods": [ { "name": "<init>", "parameterTypes": ["java.lang.String", "long"] },
{ "name": "orderId", "parameterTypes": [] }, ... ]

The other place to look is the GraalVM Reachability Metadata Repository, a shared collection of metadata for popular libraries. The native build tools for Maven and Gradle use it by default in recent versions, so if the problem is inside a well-known library rather than our own types, upgrading the plugin or the library may be all we need.

4Fixing It With Spring Runtime Hints

Copying agent output into the project works, but it is easy to let it go stale. Spring offers a code-based way to declare the same thing, and its AOT processing turns it into metadata during the build. The simplest is @RegisterReflectionForBinding, which registers a type and its members for the kind of reflection that data binding libraries such as Jackson use. For more control, a RuntimeHintsRegistrar registers types, resources and proxies programmatically and is imported with @ImportRuntimeHints.

Java
@Configuration
@RegisterReflectionForBinding({ OrderCreated.class, OrderCancelled.class })
class EventHintsConfig { }
// Or, with full control:
class EventHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.reflection().registerType(OrderCreated.class,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_METHODS,
MemberCategory.DECLARED_FIELDS);
}
}
@Configuration
@ImportRuntimeHints(EventHints.class)
class EventHintsImport { }
// After rebuilding the native image:
// toEvent(..., "OrderCreated") -> OrderCreated[orderId=A1, amountCents=4200]

Notice that the hint lives next to the code that needs it and is type-checked: renaming OrderCreated updates the hint too. When the list of event types grows, a registrar can loop over them, for example all subclasses listed in one place, so a new event cannot be forgotten.

5Catching It in CI Next Time

The failure reached run time because the JVM tests could not see it. Two kinds of test close that gap. A unit test can check the hints with RuntimeHintsPredicates on the JVM, which is fast. And native tests, mvn -PnativeTest test or gradle nativeTest, compile the test suite itself into a native executable and run it, so a test that deserializes every event type fails in CI if a hint is missing.

Java
@Test
void eventTypesAreRegistered() {
RuntimeHints hints = new RuntimeHints();
new EventHints().registerHints(hints, getClass().getClassLoader());
assertThat(RuntimeHintsPredicates.reflection().onType(OrderCreated.class)).accepts(hints); // passes
}
Step throughDiagnosing a missing class in a native image
  1. Reproduce on nativeClassNotFoundException on one path
  2. Run JVM with tracing agentexercise that path
  3. Library-internal type?
    YesCheck metadata repository, upgradeNoRegister our own hint
  4. Add RuntimeHintsRegistrar or annotationnext to the code
  5. Add hint test and nativeTestfails in CI next time

5 steps in order. Play them, or step through them one at a time.

6Follow-up questions

Why not just commit the tracing agent's output and be done?

It only records the paths we exercised, so untested paths are still missing, and it goes stale when code changes. It is excellent for discovering what is needed; code-based hints or library-provided metadata are easier to keep correct.

Could we avoid Class.forName entirely?

Often, yes. A fixed map from type names to classes, or Jackson's polymorphic handling with @JsonTypeInfo and @JsonSubTypes listing the subtypes, makes the classes visible in the code. Visible code needs fewer hints and is safer anyway, since loading arbitrary class names from messages is a security risk.

Why did Spring not register this type automatically?

Spring infers hints for types it can see in bean definitions and, in many cases, in web controller signatures. A type reached only through a string at run time is invisible to it, just as it is to native-image.

7Conclusion

In this answer, we saw that a class loaded by name was missing because native-image only includes code its static analysis can reach. We used the tracing agent on the JVM to discover the needed metadata, checked the reachability metadata repository for library types, fixed the problem with @RegisterReflectionForBinding or a RuntimeHintsRegistrar, and protected it with a hints test and native tests in CI.

What to say in the interviewAbout 80 seconds aloud

Open with

The class is missing because native-image only includes what its static analysis can reach from main. The JSON code loads the type with Class.forName on a name from the message, so the analysis can't know which class that is, and it's not in the executable.

Then, if they want more

Even if it were reachable, Jackson needs reflection on its constructor and accessors, which also has to be registered. To diagnose, I'd run the normal jar on the JVM with -agentlib:native-image-agent and push one of these messages through. The agent records every reflective access, so I can see exactly which classes and members are used.

If the missing type belongs to a third-party library, I'd check the GraalVM Reachability Metadata Repository, which the native build tools use by default, and maybe upgrade. For our own types, I'd fix it in code: @RegisterReflectionForBinding with the event classes on a configuration class, or a RuntimeHintsRegistrar that registers them with the member categories Jackson needs, imported with @ImportRuntimeHints.

Spring's AOT step turns those into metadata at build time. Finally I'd add a unit test using RuntimeHintsPredicates, and run nativeTest in CI, so the next missing hint fails the pipeline instead of production. Longer term I'd replace Class.forName with an explicit type map.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A Spring Boot native image builds successfully but fails at runtime with a...": https://scrivio-interview-library.netlify.app/spring-boot/native-and-aot/4433f85c1b/