You can build a native executable from a class file, from a JAR file, or from a module. This guide demonstrates how to build a native executable from a JAR file.
To build a native executable from a JAR file in the current working directory, use the following command:
native-image [options] -jar jarfile [executable name]
Make sure you have installed a GraalVM JDK. The easiest way to get started is with SDKMAN!. For other installation options, visit the Downloads section.
Prepare the application.
| src
| --com/
| -- example
| -- App.java
package com.example;
public class App {
public static void main(String[] args) {
String str = "Native Image is awesome";
String reversed = reverseString(str);
System.out.println("The reversed string is: " + reversed);
}
public static String reverseString(String str) {
if (str.isEmpty())
return str;
return reverseString(str.substring(1)) + str.charAt(0);
}
}
This is a small Java application that reverses a String using recursion.
javac -d build src/com/example/App.java
This produces the file App.class in the build/com/example/ directory.
jar --create --file App.jar --main-class com.example.App -C build .
It will generate a runnable JAR file, named App.jar, in the project root directory:
To view its contents, run the command jar tf App.jar
.
native-image -jar App.jar
It will produce a native executable in the project root directory.
The default name of the executable will be the name of the JAR file (“App” in this case).
It can be customized by either providing a custom name as a last argument (for example, native-image -jar App.jar executable_name
), or by using -o executable_name
before or after -jar jarfile
, for example: native-image -jar App.jar -o executable_name
.
./App
The default behavior of native-image
is aligned with the java
command which means you can pass the -jar
, -cp
, -m
options to build with Native Image as you would normally do with java
. For example, java -jar App.jar someArgument
becomes native-image -jar App.jar
and ./App someArgument
.