Sub topic 4
Why reflection and other dynamic features need help
This chapter assumes you can build a native executable with native-image, and that you know what the closed-world assumption means: the image builder only includes code it can prove is reachable at build time. You should also know basic Java reflection (Class.forName, getDeclaredConstructor).
The problem: code the analysis cannot see
Native Image runs a static analysis starting from main. It follows method calls, field accesses and class references, and it keeps only what it finds. This works well when every call is visible in the bytecode.
Dynamic features break that visibility. The target is chosen by a string, a file, or a configuration value that exists only at run time. The analysis cannot guess it, so it leaves the target out of the image.
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);
}
}On a JVM this works if Greeter is on the classpath. In a native image, Greeter may be missing from the executable, or present without its constructor. The result is a ClassNotFoundException or NoSuchMethodException at run time, not at build time.
Native Image does fold some reflection calls when the argument is a compile-time constant. A literal string passed to Class.forName can sometimes be resolved during the build. Do not rely on this. Names that come from variables, files or user input are never resolved.
Which features are affected
Several Java features share this problem. Each needs the builder to be told about its targets ahead of time.
| Feature | What the analysis cannot see | What must be declared |
|---|---|---|
| Reflection | Classes, methods and fields chosen by name | The types and which members are accessed |
| Resources | Files loaded with `getResourceAsStream` | The resource path or pattern to embed |
| Dynamic proxies | Interface combinations passed to `Proxy.newProxyInstance` | The list of interfaces |
| Serialization | Classes read through `ObjectInputStream` | The serializable classes |
| JNI | Java members called from native code | The classes and members |
Resources are the easiest to miss. A file under src/main/resources is only in the image if it is registered. Otherwise getResourceAsStream returns null, and the first symptom is often a NullPointerException far from the cause.
Why the builder cannot just include everything
Keeping every class and every member reachable by reflection would defeat the purpose. The executable would grow, startup would slow down, and dead code would stay in. The closed-world design trades convenience for a small, fast binary. So the tool asks you to state what the program needs.
Declaring a type for reflection has a cost. Registering allDeclaredConstructors and allPublicMethods keeps all of those members, along with everything they reference. Register what you use, not whole packages.
The shape of the fix
The declaration is called reachability metadata. For the example above, it is a JSON entry placed under META-INF/native-image/:
[
{
"name": "com.example.Greeter",
"allDeclaredConstructors": true,
"allPublicMethods": true
}
]With this entry the builder keeps Greeter and its constructors and public methods, so the lookup in Reflective succeeds. The next chapter covers the file formats and where each one goes.
Recognizing the symptoms
Failures from missing metadata share a pattern. They appear at run time, only in the native build, and the same code works on the JVM.
- A
ClassNotFoundExceptionfor a class you can see in your source. - A
NoSuchMethodExceptionorNoSuchFieldExceptionfor a member that exists. - A
nullfromgetResourceAsStream, or a missing-resource error from a library. - A
MissingReflectionRegistrationErrorwhen the image was built with strict checking enabled. The message names the missing element, which is the most direct clue you can get.
Libraries add to this. A JSON mapper, a dependency injection container or a logging framework may use reflection internally. You may see errors for classes you never mention in your own code. Many popular libraries now ship their own metadata, and frameworks generate it for you, which later chapters cover.
Exercise
A program calls Class.forName(name), where name is read from a configuration file at start-up. It runs correctly on the JVM but throws ClassNotFoundException in the native executable, even though the class is on the classpath at build time. Why does this happen, and what is the fix?
Show answer
The name is only known at run time, so the static analysis cannot tell the class is needed and leaves it out of the image (or keeps it without reflective access). The fix is to register the class in reachability metadata, for example a reflect-config.json entry under META-INF/native-image/, so the builder keeps it.
Exercise
Your native executable starts, but getResourceAsStream("/app.properties") returns null. The file exists in src/main/resources. What is missing?
Show answer
The resource was not registered for inclusion, so it was not embedded in the image. Add it to the resource metadata, so the builder includes it.