Sub topic 5
Declaring reachability metadata
This chapter assumes you can build a native executable with native-image. It also assumes you know the closed-world assumption and why reflection, resources and proxies are invisible to static analysis. You should be able to read JSON and know the basic layout of a Maven or Gradle project.
What reachability metadata is
Native Image builds a closed world. Its static analysis starts at your entry points and follows every call it can prove. Anything it cannot prove is removed from the executable. A reflective lookup by a runtime string, a resource read by name, or a dynamic proxy for an interface can all be impossible to prove.
Reachability metadata is information you give the builder about code and data that is reached only dynamically. It tells the builder to keep a class, a constructor, a method, a field, a resource, or a generated proxy class. Metadata does not change what your program does. It only widens the closed world so that the dynamic access still works at run time.
The failure when metadata is missing is not a build error. The program builds, then fails when it first touches the missing element.
public class Reflective {
public static void main(String[] args) throws Exception {
Class<?> c = Class.forName("com.example.Greeter");
Object o = c.getDeclaredConstructor().newInstance();
System.out.println(o);
}
}The class name here is a constant string, so the builder may resolve it. If the name came from a config file or a command-line argument, it could not. Without metadata for Greeter, the call throws ClassNotFoundException. If the class is present but its constructor is not registered, you get NoSuchMethodException instead.
Where metadata lives
The builder looks for metadata in the META-INF/native-image/ directory on the classpath. This works for your own project and for dependency JARs, so a library can ship its own metadata and you get it for free.
By convention, files go in a subdirectory named after the Maven coordinates:
META-INF/native-image/<groupId>/<artifactId>/The coordinates prevent two JARs from overwriting each other's files. Inside that directory, the builder reads these files.
| File | What it declares |
|---|---|
| `reflect-config.json` | Classes, constructors, methods and fields available to reflection |
| `resource-config.json` | Classpath resources and resource bundles to embed in the image |
| `proxy-config.json` | Interface lists for which dynamic proxy classes are generated |
| `serialization-config.json` | Classes that Java serialization may read or write |
| `jni-config.json` | Classes, methods and fields accessed from native code through JNI |
| `native-image.properties` | Extra builder arguments, such as initialization options |
Recent GraalVM releases also support a single combined file, reachability-metadata.json, which holds reflection, resources, serialization, JNI and proxy entries as sections of one document. The ideas are the same. This chapter uses the per-feature files, because most existing projects and libraries still use them. Check the documentation for the GraalVM version you build with before choosing a format.
Declaring reflection
A reflect-config.json file is an array of entries. Each entry names a class and says which of its members must stay reachable through reflection.
[
{
"name": "com.example.Greeter",
"allDeclaredConstructors": true,
"allPublicMethods": true
}
]This entry keeps the class com.example.Greeter. It keeps all constructors declared in it, and all of its public methods. That is enough for the Reflective program above to create an instance.
You can be more precise. Name individual methods and fields instead of using the all... flags:
[
{
"name": "com.example.Greeter",
"methods": [
{ "name": "<init>", "parameterTypes": [] },
{ "name": "greet", "parameterTypes": ["java.lang.String"] }
],
"fields": [
{ "name": "prefix" }
]
}
]The constructor is named <init>. Parameter types are fully qualified class names, and primitives use their plain names such as int.
The trade-off is size against safety. The all... flags are easy to write and rarely miss something, but each one pulls in more code and makes the executable larger. Individual entries produce a smaller image, but a missed member fails only at run time.
Declaring resources
Resources are files read from the classpath, such as .properties files, templates or SQL scripts. The builder does not embed them unless you ask. A program that reads a resource normally works on the JVM, then gets null from getResourceAsStream in the native executable.
import java.io.InputStream;
import java.util.Properties;
public class ReadConfig {
public static void main(String[] args) throws Exception {
try (InputStream in = ReadConfig.class
.getResourceAsStream("/config/app.properties")) {
if (in == null) {
System.out.println("resource not found");
return;
}
Properties p = new Properties();
p.load(in);
System.out.println(p.getProperty("name"));
}
}
}A matching resource-config.json lists the resource by pattern. Patterns are regular expressions that match the full resource path. The \Q...\E form quotes the text literally, so the dots in the name are not wildcards:
{
"resources": {
"includes": [
{ "pattern": "\\Qconfig/app.properties\\E" }
]
},
"bundles": [
{ "name": "messages" }
]
}The bundles entry registers a resource bundle by base name, for example messages for messages_en.properties and its siblings. Without it, ResourceBundle.getBundle fails in the executable.
A pattern such as .*\\.properties$ includes every properties file on the classpath. That is convenient and also grows the image, so prefer narrower patterns.
Proxies and serialization
Java's java.lang.reflect.Proxy creates a class at run time that implements a list of interfaces. The native image cannot generate classes at run time, so each interface list used with a proxy must be declared. In proxy-config.json, each entry is one interface list, and the order of interfaces matters. A Proxy call with [A, B] does not match an entry for [B, A].
Serialization works the same way. Java serialization reads and writes class descriptions that the builder must know about. Classes you serialize or deserialize through ObjectInputStream and ObjectOutputStream go in serialization-config.json. Records and plain classes that use only JSON libraries do not need this file, but the JSON library itself usually needs reflection metadata for your data classes.
Providing metadata in code
Static JSON files are the common approach, but you can also register metadata from a build-time hook called a Feature. This helps when the list of classes is computed, for example from a naming convention.
import org.graalvm.nativeimage.hosted.Feature;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
public class GreeterFeature implements Feature {
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
try {
Class<?> c = Class.forName("com.example.Greeter");
RuntimeReflection.register(c);
RuntimeReflection.register(c.getDeclaredConstructors());
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
}
}You enable it with the builder option --features=GreeterFeature and put the compiled class on the builder's classpath. The org.graalvm.nativeimage API comes from the org.graalvm.sdk dependency, used at the provided scope. Prefer JSON when it is enough, because JSON is readable by tools and by the agent chapter that follows.
Metadata for third-party libraries
You usually do not write metadata for libraries. There are three sources:
- The library JAR may already contain
META-INF/native-image/files. - The community GraalVM Reachability Metadata Repository holds metadata for many popular libraries. The Maven and Gradle native plugins can download it for you when it is enabled. The next build-tools chapter shows the setting.
- Your framework may generate metadata at build time. This is the case for Spring Boot, Quarkus and Micronaut.
If none of these covers a library, you write the missing entries yourself or collect them with the tracing agent.
Working through a missing-metadata failure
A typical loop looks like this:
- Build the image and run it with a realistic workload.
- Read the exception. The class name, member or resource name in the message is the entry you need.
- Add the entry to the right file under
META-INF/native-image/. - Rebuild and run again.
Every iteration costs a full build, so this loop is slow. Collecting entries with the agent is faster, and gives better coverage than guessing.
Common mistakes
- Placing files outside
META-INF/native-image/, so the builder never reads them. - Forgetting that each subtype used reflectively needs its own entry. Registering an interface does not register its implementations.
- Registering a class but not its members, which gives
NoSuchMethodExceptionat run time. - Using the wrong resource path form, as described above.
- Writing the interface list for a proxy in a different order than the program uses.
- Using inner class names without the binary form. A nested class is
com.example.Outer$Inner.
Exercise
Your image prints "resource not found" for getResourceAsStream("/templates/mail.html"), though the same code works on the JVM. Which file do you edit, and what entry do you add?
Show answer
Edit resource-config.json under META-INF/native-image/<groupId>/<artifactId>/. Add an include entry whose pattern matches the path without the leading slash, for example { "pattern": "\\Qtemplates/mail.html\\E" } inside resources.includes. Then rebuild the image, because resources are embedded only at build time.
Exercise
A reflection entry for com.example.Greeter sets only "name": "com.example.Greeter", with no member flags. The program calls getDeclaredConstructor().newInstance() on it. What error do you expect, and how do you fix it?
Show answer
The class is found, but its constructor is not registered, so the call throws NoSuchMethodException. Add "allDeclaredConstructors": true, or list a method entry named <init> with its parameter types.