This documentation is for an old GraalVM version. See the latest version.

Build a Native Executable from a JAR File

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]
  1. 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.

  2. Prepare the application.

    • Create a new Java project named “App”, for example in your favorite IDE or from your terminal, with the following structure:

        | src
        |   --com/
        |      -- example
        |          -- App.java
      
    • Add the following Java code to the src/com/example/App.java file:

        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.

  3. Compile the application:
     javac -d build src/com/example/App.java
    

    This produces the file App.class in the build/com/example directory.

  4. Create a runnable JAR file:
     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.

  5. Create a native executable:
     native-image -jar App.jar
    

    It will produce a native executable in the project root directory.

  6. Run the native executable:
     ./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.

Connect with us