Sub topic 4
Why reflection and other dynamic features need help
This chapter assumes you have built a native executable with native-image and know what the closed-world assumption means. You should also be comfortable with Class.forName, getResourceAsStream, and java.lang.reflect.Proxy on a normal JVM.
A program that works on the JVM can fail in a native image even though it compiled cleanly. The cause is usually a dynamic feature. The build tool could not see that your code needed a class, a method, a file, or a proxy, so it left that item out of the executable.
The problem in one sentence
Native Image decides what goes into the executable by analyzing the code before the program runs. Dynamic features pick their targets while the program runs, often from a string. The analysis cannot read a string that does not exist yet.
On the JVM this is not a problem, because the whole class path is available at run time. The JVM can load any class, read any resource, and generate a proxy class whenever your code asks. A native image has no class loader that can find new classes, no bytecode to interpret, and no JIT compiler to produce new code. Whatever was not compiled in is gone.
A quick recap of what the analysis sees
The static analysis starts at the entry point (main) and follows every call that can be reached. Classes, methods and fields found this way are compiled into the image. Everything else is removed.
This works well for ordinary calls such as list.add(x), where the target is named in the code. It breaks down when the target is computed:
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 next sections explain why this program is a problem and when it is not.
Reflection
Reflection lets code inspect and use classes by name. The common entry points are:
Class.forName(String)Class.getDeclaredConstructor(),getMethod,getDeclaredFieldMethod.invoke,Constructor.newInstance,Field.getandField.set
Each call needs a native image to contain three things: the class itself, the member you ask for, and the information that reflection is allowed to reach it. A class that is never referenced in code is not reachable, so it is not included at all.
A constant name is sometimes enough
Native Image can fold some reflective calls whose arguments are compile-time constants. In the example above, the string "com.example.Greeter" is a literal, so the build may recognize the call and register the class itself. Do not depend on this. It works only when the whole argument chain is constant, and it differs between versions.
The realistic case is a name that comes from a configuration file, a command-line argument, or a framework annotation. Here is a complete version that you can try:
package com.example;
public class Greeter {
public Greeter() {
}
@Override
public String toString() {
return "Hello from Greeter";
}
}public class Reflective {
public static void main(String[] args) throws Exception {
String name = args.length > 0 ? args[0] : "com.example.Greeter";
Class<?> c = Class.forName(name);
Object o = c.getDeclaredConstructor().newInstance();
System.out.println(o);
}
}Save Greeter.java as com/example/Greeter.java and Reflective.java in the current directory. Then build and run:
javac -d out com/example/Greeter.java Reflective.java
java -cp out Reflective
native-image -cp out Reflective
./reflectiveThe JVM run prints Hello from Greeter. The native run fails with java.lang.ClassNotFoundException: com.example.Greeter. The class file exists on the class path at build time. Nothing in the reachable code refers to Greeter by name, so the analysis never included it.
Missing members
Registering a class is not enough. Reflection also needs to know which constructors, methods and fields to keep. If the class is registered but the method you ask for is not, you get a NoSuchMethodException (or a similar error, depending on the version and build flags). Newer GraalVM releases can report this as a clear "missing registration" error that names the element, which makes the fix easier.
Resources
A resource is a non-class file on the class path, such as application.properties, a template, or a certificate. On the JVM, getResourceAsStream looks inside JARs and directories. A native image does not carry the class path with it. Only resources that you declare are copied into the 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("/app.properties")) {
if (in == null) {
System.out.println("app.properties not found");
return;
}
Properties p = new Properties();
p.load(in);
System.out.println(p.getProperty("greeting"));
}
}
}On the JVM this prints the property value. In a native image that lacks the resource declaration, getResourceAsStream returns null and the program takes the "not found" branch. There is no exception, so this failure is easy to miss.
Dynamic proxies
java.lang.reflect.Proxy.newProxyInstance generates a class at run time that implements a list of interfaces. A native image cannot generate classes at run time. It can only use proxy classes that were created during the build, which means the exact interface list must be known and declared in advance.
The order of the interfaces matters. A proxy for [A, B] is a different class from a proxy for [B, A]. Libraries that use proxies, such as those for declarative HTTP clients or transaction handling, usually need entries for each interface combination they create.
Serialization, JNI and other cases
Several other features share the same problem. Each one has its own kind of metadata.
| Feature | What goes wrong without help | Metadata kind |
|---|---|---|
| Reflection | Class or member not found | reflection entries |
| Resources | `getResourceAsStream` returns `null` | resource entries |
| Dynamic proxies | Proxy class missing for an interface list | proxy entries |
| Java serialization | Class cannot be written or read by `ObjectInputStream` | serialization entries |
| JNI | Native code cannot find Java classes or methods by name | JNI entries |
Other features are partly handled by the build tool itself. For example, ServiceLoader providers are discovered from META-INF/services files in many cases. Resource bundles and some security providers need explicit attention. Check the documentation for your GraalVM version rather than assuming.
Features that need runtime code generation are not supported at all. Loading new bytecode with a custom ClassLoader.defineClass, or generating classes with a library such as ByteBuddy at run time, cannot work, because the image has no way to load or compile new bytecode. Libraries that do this need a different approach, such as generating the classes at build time.
How the failure happens
The following diagram shows why the build succeeds and the run fails.
The key point is the branch at the question. The analysis only includes what it can prove is needed. Metadata gives it the proof it cannot compute itself.
What the fix looks like
You give the analysis the missing facts as configuration files placed under META-INF/native-image/ on the class path. For the Greeter example, this reflection entry keeps the constructors and public methods available:
[
{
"name": "com.example.Greeter",
"allDeclaredConstructors": true,
"allPublicMethods": true
}
]With this file in place, the build includes Greeter and the executable prints Hello from Greeter. How to write these files, which options exist, and how conditions limit them is the topic of the next chapter. Chapter after that shows how the tracing agent records the entries for you by watching a normal JVM run.
Decision guidance
Dynamic features are not forbidden. They have a cost, and you can manage it:
- Prefer direct calls when the target is known. A plain
new Greeter()needs no metadata and gets better analysis and dead-code removal. - If reflection is needed, register the smallest set of classes and members. Each entry keeps code in the image and increases its size.
- Treat the native test run as part of your test suite. A missing registration shows up only when that code path executes.
- When choosing a library, check whether it supports native images. A library that is heavy on reflection and runtime proxies can cost you more time than it saves.
Exercise
A service reads a class name from config.properties and loads it with Class.forName. The native image builds without errors but fails on startup with ClassNotFoundException. The same JAR works on the JVM. Explain the cause in two sentences, and name one change that fixes it.
Show answer
The class name only exists in a file read at run time, so the static analysis never saw a reference to that class and left it out of the image. Registering the class as reflection metadata (for example a reflect-config.json entry under META-INF/native-image/) makes the build include it.
Exercise
Your native executable runs without exceptions, but a feature that loads templates from /templates/welcome.html behaves as if the file is empty. The file is on the class path and works on the JVM. What is the likely cause, and why did no exception appear?
Show answer
The resource was not declared, so it was not copied into the image. getResourceAsStream returns null for a missing resource instead of throwing, so the program continues and the failure shows up only through the null handling. The fix is to include the resource through resource metadata.