Sub topic 2
Declaring Reachability Metadata
Assume you can compile Java, use JARs and the classpath, and have basic Maven or Gradle experience. Native Image performs static analysis, so it must know which classes, methods, resources, and proxies the program can reach.
Declaring reachability metadata
Reflection hides calls from static analysis. For example, Class.forName names a class at runtime:
Class<?> type = Class.forName("com.example.Greeter");
Object greeter = type.getDeclaredConstructor().newInstance();Register the required members in META-INF/native-image/reflect-config.json:
[
{
"name": "com.example.Greeter",
"allDeclaredConstructors": true,
"allPublicMethods": true
}
]Other metadata files describe resources, dynamic proxies, and Java serialization. Place these files under META-INF/native-image/ in the application or a dependency JAR.
Collecting metadata with the tracing agent
The tracing agent observes a normal JVM run and records dynamic usage:
java -agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image \
-jar app.jarExercise the important application paths while this command runs. The agent can write reflection, resource, proxy, and serialization configuration. Review the generated files before committing them. The agent records observed behavior, so an untested code path can still fail in the native executable.
Class initialization at build time and run time
Native Image may execute eligible static initialization during the image build. This can improve startup, but it freezes state such as timestamps, random values, or environment-dependent configuration.
Use explicit options when necessary:
native-image \
--initialize-at-build-time=com.example.ImmutableConfig \
--initialize-at-run-time=com.example.RuntimeConfig \
-jar app.jarBuild-time initialization is suitable for deterministic, immutable setup. Use run-time initialization when code depends on the deployment environment or maintains runtime state.
Building with Maven and Gradle
The GraalVM build plugins integrate native compilation into common workflows. A Maven profile can add the native plugin:
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>${native.maven.plugin.version}</version>
<extensions>true</extensions>
</plugin>Build with mvn -Pnative native:compile. With Gradle, apply the GraalVM Native Build Tools plugin and run ./gradlew nativeCompile. Both tools pass metadata and initialization settings to native-image.
Exercise
Why can a class used only through reflection be missing from a native image?
Show answer
Static analysis cannot see the reflective call, so the class or its members need reachability metadata or agent-generated configuration.