Skip to content
javahacks.dev
Quarkus

Fix Quarkus Native Image Build Failures With Reflection

Fix a Quarkus native executable that builds and then fails at runtime with missing classes or methods, by registering classes for reflection correctly.

6 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the Quarkus, OpenJDK and Spring logos.

The JVM tests pass, the native build succeeds and the executable fails on the first request:

Text
java.lang.ClassNotFoundException: dev.javahacks.invoice.InvoiceDto

or

Text
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class dev.javahacks.invoice.InvoiceDto and no properties discovered to create BeanSerializer

GraalVM's native image compiler does a closed-world analysis: it keeps what it can prove is reachable. Reflection is invisible to that analysis, so a class that a library reads reflectively is dropped unless you say otherwise. Quarkus extensions declare what they know about. Your own classes are yours to declare. The context is in Quarkus for Spring developers, and the reason JVM mode hides the problem is in build-time processing.

Fix 1: @RegisterForReflection on your classes

java
@RegisterForReflection
public record InvoiceDto(String id, long totalCents) { }

This keeps the class, its constructors, fields and methods. Quarkus REST with Jackson registers the types returned from resource methods automatically, so the failure appears for types used elsewhere: messages sent to Kafka, JSON read by a client, objects serialized inside a service.

Register a group of classes in one place:

java
@RegisterForReflection(targets = { InvoiceDto.class, PaymentDto.class })
class ReflectionConfig { }

Fix 2: classes you cannot annotate

For a class in a library, point to it by name:

java
@RegisterForReflection(targets = com.thirdparty.Model.class, classNames = "com.thirdparty.internal.Hidden")
class ThirdPartyReflection { }

or provide a JSON reflection configuration file and reference it:

properties
quarkus.native.additional-build-args=-H:ReflectionConfigurationFiles=reflection-config.json

Place reflection-config.json in src/main/resources. The file lists classes and the members to keep.

Fix 3: resources and proxies

Files read from the classpath must be included:

properties
quarkus.native.resources.includes=templates/**,config/*.json

JDK dynamic proxies for interfaces that you create at runtime need registration as well; the CDI container handles its own.

Find out what is missing

Run the native binary against the same scenarios as the JVM tests. Quarkus supports this directly:

java
@QuarkusIntegrationTest
class InvoiceResourceIT extends InvoiceResourceTest { }

The integration test starts the built executable and runs the inherited tests against it. That catches reflection gaps before production does. The GraalVM tracing agent can record the reflection a JVM run uses and write a configuration file: run the application on the JVM with -agentlib:native-image-agent=config-output-dir=... and exercise it.

Build-time failures are a different class

If the build itself fails, the message names the problem:

MessageMeaning
Classes that should be initialized at run time got initialized during image buildingA static initializer ran at build time; defer it with --initialize-at-run-time
Unsupported features in ...Code uses a feature the compiler cannot handle, such as a certain MethodHandle use
Out of memoryThe build needs more heap; give the builder more memory or run it in a container

Container builds are the usual way to get a Linux binary from another platform; see quarkus.native.container-build=true.

Understand the two kinds of failure

A native build can fail while compiling, or the compiled executable can fail while running, and the fixes differ. A compile-time failure prints a message from the native image builder and stops. A run-time failure is the more common and more confusing one: the build succeeds, the executable starts, and the first request throws an error such as NoSuchMethodException, ClassNotFoundException, or a serialization library reporting that it cannot instantiate a class. Both have the same root. The native image compiler includes only the code it can prove is reachable, and reflection, resources loaded by name and dynamic proxies are invisible to that analysis unless declared.

The practical consequence is that a native build must be exercised through the native executable, not only on the JVM. A failure that is absent in the JVM test run appears in mvn verify -Dnative, which runs the integration tests against the built binary.

Shell
./mvnw verify -Dnative
./mvnw package -Dnative -Dquarkus.native.container-build=true

The second command builds inside a container, which removes the need for a local GraalVM or Mandrel installation and makes the result match a Linux server even when you develop on a Mac or Windows machine.

Register the types that frameworks reach by name

The usual source of a run-time failure is a data class serialized to JSON or loaded by a framework through reflection. Quarkus can register it for reflection with an annotation, and the annotation is the first thing to try.

java
@RegisterForReflection
public record OrderView(long id, String status, BigDecimal total) { }

For types you cannot annotate, such as classes from a library, list them on a placeholder class, or in the configuration:

java
@RegisterForReflection(targets = { com.vendor.client.Response.class, com.vendor.client.ErrorBody.class })
public class ReflectionConfiguration { }
src/main/resources/application.propertiesproperties
quarkus.native.additional-build-args=--initialize-at-run-time=com.vendor.client.Crypto
quarkus.native.resources.includes=templates/**,messages/*.properties

The resources line addresses the other common case: a file read from the class path at run time (a template, a properties bundle, a JSON schema) is left out of the image unless it matches an include pattern. A NullPointerException from getResourceAsStream that appears only in the native executable is this problem.

Let the agent find what is missing

When a library does a lot of reflection and the error messages do not say which class is needed, run the application on the JVM with the native image agent. It watches what reflection, resources and proxies the program actually uses during a run, and writes configuration files that you can review and keep.

Shell
java -agentlib:native-image-agent=config-output-dir=target/agent-config -jar target/quarkus-app/quarkus-run.jar
# exercise every endpoint, then stop the application
ls target/agent-config

The output includes reflect-config.json, resource-config.json, proxy-config.json and others. Copy the entries you need into src/main/resources/META-INF/native-image/<group>/<artifact>/, where the builder picks them up automatically. The agent records only the paths you exercised, so a rarely used code path is missing from the result; run the application's tests through the agent, not just a manual click-through, to cover more. Review the files: they may list classes from test libraries, and a few hundred lines that nobody understands are a maintenance burden, so keep only what the application needs.

A short debugging loop

When a native executable fails, shorten the cycle. Build in quick mode while iterating (-Dquarkus.native.additional-build-args=-Ob), read the stack trace for the first missing class or resource, add the registration, and rebuild. Enable --report-unsupported-elements-at-runtime only for diagnosis; it turns build-time errors into run-time ones and hides problems. Keep a test that calls the endpoints that return the types you registered, running against the native binary, so the next dependency upgrade that changes a class name fails in CI and not in production.

Where this does not apply

If the application works on the JVM and you never need native, you can ignore this entire category. A long-running service with a warm JIT often performs as well in JVM mode. The Quarkus native tips guide and the native image guide cover registration in full. For deployment choices see Quarkus vs the JVM trade-offs.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.