Sub topic 9
Reachability metadata for reflection, resources and proxies
This chapter assumes you know Java reflection and dynamic proxies at a conceptual level, can build a Spring Boot project with Maven or Gradle, and have read the chapter on the closed-world assumption. Here you will learn what reachability metadata is, what it contains, where it comes from, and what happens when it is missing.
Why metadata exists
GraalVM native-image analyzes your program at build time and keeps only the code it can prove is reachable. This is the closed-world assumption. Ordinary method calls are easy to follow. Some Java features are not, because their targets are decided at run time:
- Reflection:
Class.forName("com.example.Greeting"),getDeclaredMethod(...), or a framework that reads field names from a string. - Resources:
getResourceAsStream("templates/greeting.txt"). The analysis cannot tell which files on the classpath you will ask for. - Dynamic proxies:
java.lang.reflect.Proxy.newProxyInstance(...)generates a class at run time from a list of interfaces. Native images have no run-time class generation, so the proxy class must be created during the build. - JNI and serialization: native code calls back into Java, or Java serialization needs to know which classes to handle.
For each of these, the build needs a declaration of what will be used. That declaration is reachability metadata. Without it, the class is removed, the resource is left out of the executable, or the proxy class is never generated.
What the metadata describes
Metadata is a set of JSON files under META-INF/native-image/<groupId>/<artifactId>/. The tool reads every such directory on the classpath, so libraries can ship their own metadata and you inherit it automatically. The main files are:
| File | Declares | Typical trigger |
|---|---|---|
| `reachability-metadata.json` | All categories in one file (newer GraalVM versions) | Any |
| `reflect-config.json` | Classes, constructors, methods and fields reachable by reflection | `Class.forName`, `getMethod`, JSON binding |
| `resource-config.json` | Classpath resources to include | `getResource`, `getResourceAsStream` |
| `proxy-config.json` | Interface lists for which a proxy class is generated | `Proxy.newProxyInstance`, `@Transactional` JDK proxies |
| `serialization-config.json` | Classes used with Java serialization | `ObjectInputStream` |
| `jni-config.json` | Classes and members used from native code | JNI |
Older GraalVM releases use the separate *-config.json files. Newer releases consolidate them into reachability-metadata.json. The content is the same idea in either format, and the tools read both.
A minimal reflect-config.json looks like this:
[
{
"name": "com.example.AppConfig$Greeting",
"allDeclaredConstructors": true,
"allPublicMethods": true
}
]A matching resource-config.json for a template file:
{
"resources": {
"includes": [
{ "pattern": "\\Qtemplates/greeting.txt\\E" }
]
}
}The pattern is a regular expression, and \Q...\E quotes the file name literally.
What happens when metadata is missing
Missing metadata does not fail the build. The program compiles, and the failure appears only when the code path runs. The symptoms are specific:
| Missing metadata | Typical symptom |
|---|---|
| Reflection | `ClassNotFoundException`, `NoSuchMethodException`, or a framework reporting a class it cannot instantiate |
| Resource | `getResourceAsStream` returns `null`, followed by a `NullPointerException`, or a `FileNotFoundException` |
| Proxy | `MissingReflectionRegistrationError` or an error that a proxy class for a list of interfaces was not found at build time |
A reflection failure is easy to misread. If a class is not registered, Class.forName throws ClassNotFoundException even though the class exists in your source. This happens because the class was never put into the executable, not because of a typo.
Where metadata comes from in a Spring Boot application
You rarely write all of it by hand. Four sources contribute, and they are merged during the build.
- Spring AOT processing. During the build, Spring inspects your bean definitions and generates both initialization code and hints. For example, it registers reflection hints for
@ConfigurationPropertiesclasses and for controller methods. You get this for free. - Library-supplied metadata. Many libraries ship files inside their JARs. Spring Boot's starters rely on this for the libraries they wrap.
- The GraalVM Reachability Metadata Repository. The
org.graalvm.buildtools.nativeplugin downloads community-maintained metadata for popular libraries that do not ship their own. It is enabled by default in the Spring Boot native profile. - Your own declarations. Anything specific to your code, such as a class you load by name or a resource you read from the classpath, is your responsibility. You can write it as JSON, with Spring
RuntimeHints(next chapter), or collect it with the tracing agent (the chapter after).
Granularity: how much to register
Metadata can be narrow or broad. A narrow entry keeps the executable small. A broad entry is safer against missed cases.
- For reflection, you choose per class which members are exposed.
allDeclaredConstructorsorallPublicMethodsregisters many members at once. Listing individual methods registers only those. - For resources, you choose a pattern. A pattern like
templates/.*includes every file under that directory, while an exact name includes one file. - For proxies, the entry is the exact ordered interface list. A proxy for
[A, B]is a different entry from one for[B, A].
Registering a class for reflection also keeps it from being removed, so it enlarges the image. Every unneeded entry costs a small amount of size and build time, so avoid registering whole packages out of caution.
A worked example: a resource that disappears
Suppose a service reads a template at startup.
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class TemplateLoader {
public String load() throws IOException {
try (InputStream in = TemplateLoader.class
.getResourceAsStream("/templates/greeting.txt")) {
if (in == null) {
throw new IllegalStateException("Resource not found: templates/greeting.txt");
}
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
}
}On the JVM, this works because the file is inside the JAR. In a native executable built without metadata, the file is not embedded, so in is null and the guard throws. The fix is to declare the resource, either with a resource-config.json as shown above or with a RuntimeHintsRegistrar calling hints.resources().registerPattern("templates/greeting.txt").
Note the explicit null check. Failing with a clear message is much easier to diagnose than a bare NullPointerException further along.
Common errors
- Assuming the JVM behavior carries over. A test that passes on the JVM says nothing about metadata. Run native tests to find gaps.
- Registering a class but not the members used. Registering
Greetingwith no member categories allowsClass.forNamebut notgetDeclaredConstructor().newInstance(). - Forgetting nested and inner classes.
AppConfig$Greetingis a separate class fromAppConfig, and needs its own entry. - Wrong proxy interface order. The proxy list must match what the code requests.
- Resource paths with a leading slash. Patterns in metadata are relative to the classpath root, with no leading
/. - Hand-edited generated files. If you regenerate agent output, your edits are overwritten. Keep manual metadata in a separate directory or in Java hints.
Checking that metadata was applied
A quick check is to build and run the code path that needs the metadata. For a more direct look, inspect what the build processed. Spring's AOT step writes generated hints into target/spring-aot/main/resources/META-INF/native-image/ for Maven, so you can read them and confirm your entry is there.
find target/spring-aot -name "*.json" -path "*native-image*"If your entry appears in the output files but the call still fails, the pattern or member category probably does not match what the code actually requests.
Exercise
A native executable throws ClassNotFoundException for com.example.plugins.CsvExporter, which your code loads with Class.forName(name) using a name read from a property file. The class exists in the project and the same code works on the JVM. What is the cause, and what two pieces of information must the fix declare?
Show answer
The class was never added to the executable because the closed-world analysis cannot see a class name that is only known at run time. The fix must declare the class itself (com.example.plugins.CsvExporter) as reachable for reflection, and the members the code uses, for example its public constructors so that getDeclaredConstructor().newInstance() works. Declare it in reflect-config.json or with a RuntimeHintsRegistrar, then rebuild.
Exercise
You add templates/greeting.txt to resource-config.json and rebuild, but getResourceAsStream("/templates/greeting.txt") still returns null. List two things you would check.
Show answer
First, check that the pattern is relative to the classpath root and matches the file path exactly, with no leading slash and with regex characters quoted. Second, check that the JSON file sits under META-INF/native-image/ on the classpath (or in a generated hints directory) and that the executable was actually rebuilt, since metadata is only read at build time.