Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 38 ยท Testing and Native Images

Native Image Pitfalls and Reflection Configuration

Fix common GraalVM native image problems in Micronaut: reflection, resources, @ReflectiveAccess, @Introspected, serialization, build-time vs run-time init and debugging missing metadata.

An application that works on the JVM can fail as a native executable with errors such as ClassNotFoundException for a class you can see in your source, an empty resource, or a JSON mapper that suddenly returns nothing. The cause is almost always the same: something was used dynamically, so the build-time analysis never saw it. This lesson shows how to recognise those cases and fix them.

The tools here are not available on this site, so the real configuration is read-only. The runnable examples use plain Java to demonstrate the underlying difference between direct and dynamic access, and a checklist-style diagnostic.

Why dynamic access breaks

Look at these two lines:

Java
Note n = new Note("a");                       // direct: the compiler sees Note
Object o = Class.forName(name).getConstructor().newInstance();   // dynamic: name is a runtime string

Native image can follow the first line. For the second, name could be anything; unless you register the possible classes, the analysis removes them and the call fails. The same applies to:

  • Reflection (Class.forName, getMethod, getDeclaredFields).
  • Dynamic proxies (Proxy.newProxyInstance).
  • Resources loaded from the classpath by name (getResourceAsStream("/templates/a.html")).
  • Serialization frameworks that discover fields by reflection (Jackson without Micronaut Serde, Java serialization).
  • JNI and some SPI (ServiceLoader) lookups.

Dynamic access, and the fix

Reflection @ReflectiveAccess or reflect-config.json
Resources resource-config.json or @Requires(resources)
1 / 2

Prefer compile-time features

Micronaut gives you compile-time alternatives so you rarely need manual configuration:

  • Introspection: annotate a type with @Introspected and Micronaut generates a BeanIntrospection that reads and writes properties without reflection. Validation (see Bean Validation) and typed configuration use it.
  • Serialization: Micronaut Serialization (micronaut-serde-jackson) uses @Serdeable types and generates serializers at build time, replacing runtime-reflection Jackson. Mark request and response types @Serdeable:
Java
import io.micronaut.serde.annotation.Serdeable;

@Serdeable
public record Note(long id, String title) {}
  • AOP and proxies: Micronaut's @Transactional, @Cacheable and @Retryable generate their subclasses at compile time, so no runtime proxy is needed.

Declaring reflection

When you must use reflection on your own class (or a library class), tell the compiler. The shortest way is an annotation:

Java
import io.micronaut.core.annotation.ReflectiveAccess;

@ReflectiveAccess
public class LegacyPlugin { /* instantiated by name from configuration */ }

Or use @TypeHint to register external classes in one place:

Java
@TypeHint({ org.example.ThirdPartyType.class })
public class Application { /* ... */ }

For full control, place JSON in src/main/resources/META-INF/native-image/com.example/notes/reflect-config.json:

JSON
[
  {
    "name": "com.example.LegacyPlugin",
    "allDeclaredConstructors": true,
    "allPublicMethods": true
  }
]

Resources are declared the same way, in resource-config.json:

JSON
{ "resources": { "includes": [ { "pattern": "\\Qtemplates/welcome.html\\E" } ] } }

Micronaut can also include resources automatically if they match a pattern in micronaut.graalvm.resources.includes.

Class initialization

Static initializers either run at build time (their results are frozen into the image) or at run time. A static field that reads the current time, an environment variable or a random seed during build time would then keep a stale value forever. Micronaut initializes at run time by default for safety. Do not initialize secrets, clocks or random generators at build time; if a library requires it, you can set --initialize-at-run-time=com.example.Foo in the build configuration.

Debugging missing metadata

  1. Run the tests on the JVM first. If it fails there, native is not the problem.
  2. Run nativeTest to run your normal test suite against the native build; it exposes missing configuration early.
  3. Use the tracing agent. Start the JVM app with -agentlib:native-image-agent=config-output-dir=..., exercise the features, and the agent writes reflect-config.json and friends for everything that was used dynamically.
  4. Read the error. Messages like Class ... not found: Unable to find ... in reflection configuration name the exact class to register.
  5. Check the library. Many popular libraries now ship their own native metadata, and the GraalVM Reachability Metadata Repository supplies it for others; Micronaut's Gradle plugin enables it.

Try it: a registry of reflective classes

This stand-in models the rule: a class can be created by name only if it is registered. Everything else fails the way an unregistered class fails in a native image.

Java Registered vs unregistered

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: a checklist for a native build

This diagnostic function classifies a list of constructs in your code and prints the recommended fix for each one.

Java Which fix do I need?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Good practice

  • Add nativeTest to your CI pipeline from the start; fixing one failure early is easy, fixing fifty later is not.
  • Keep third-party dependencies modest. Each library is a source of reflection.
  • Avoid code that inspects types at runtime to decide what to do; use interfaces and beans instead (see Beans and Singletons).
  • Treat native as an optimisation you verify with measurements, not a goal in itself.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does Class.forName(name) fail in a native image for an unregistered class?

    Native image keeps only reachable code. A class named by a runtime string must be registered.
  2. 2. Which annotation generates reflection-free property access for a type?

    @Introspected makes Micronaut generate a BeanIntrospection at compile time.
  3. 3. What does the native-image tracing agent do?

    Running the app with the agent produces reflect-config.json and resource-config.json files.
  4. 4. Why should secrets and random seeds not be initialized at build time?

    Build-time initialization stores the result in the image, so every run would see the same value.

Summary

  • Native image removes code it cannot see; dynamic features (reflection, resources, proxies, serialization) need declarations.
  • Prefer Micronaut's compile-time features: @Introspected, @Serdeable and generated AOP.
  • Use @ReflectiveAccess, @TypeHint or JSON config files when you truly need reflection.
  • Run nativeTest, use the tracing agent and read error messages to find missing metadata.

Next: Project: Notes API