Sub topic 1
From bytecode on a JVM to a standalone executable
Prerequisites
Assume you can compile and run Java programs, use JAR files, and understand that the JVM uses just-in-time (JIT) compilation to optimize bytecode while an application runs.
From bytecode to native code
A normal Java application compiles to bytecode, an instruction format stored in .class files or JARs. The JVM loads that bytecode, checks it, and runs it. Its JIT compiler can turn frequently used methods into machine code during execution.
GraalVM Native Image uses ahead-of-time (AOT) compilation instead. It analyzes the application during the build and produces a platform-specific executable. The executable contains the application, selected library code, and a native runtime. It does not need a JVM to start.
Building and running your first native image
Install a GraalVM distribution that provides the native-image command, then compile this class:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, native image!");
}
}Run the following commands in the same directory:
javac Hello.java
native-image Hello
./helloThe first command creates bytecode. The second analyzes that bytecode and creates an executable named hello. The last command runs it without starting a separate JVM.
For an executable JAR, use:
native-image -jar app.jar -o appThe build usually takes longer than compiling a JAR because Native Image performs extensive analysis and compilation.
The closed-world assumption
Native Image uses a closed-world assumption: the complete set of code needed at run time is determined during the build. Static analysis follows reachable calls and removes code it cannot reach. This reduces startup work and often reduces memory use, but it limits code that appears only dynamically.
Reflection and other dynamic features
Reflection is a Java feature that looks up classes, methods, or fields by name at run time. Static analysis cannot always discover such usage:
Class<?> type = Class.forName("com.example.Greeter");
Object value = type.getDeclaredConstructor().newInstance();This code needs reachability metadata so Native Image preserves the class and constructor. Metadata can also be required for resources, dynamic proxies, and serialization.
A reflect-config.json file under META-INF/native-image/ can declare required members:
[
{
"name": "com.example.Greeter",
"allDeclaredConstructors": true,
"allPublicMethods": true
}
]Exercise
Why can a native executable start quickly but fail when it first uses reflection?
Show answer
Native Image removes code that static analysis cannot prove is reachable. Reflection metadata must preserve the required class and members.