Skip to Content
Course content

180: Native Image Compilation with GraalVM

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've probably heard the pitch for GraalVM Native Image: lightning-fast startup times and a tiny memory footprint. It sounds like magic because it basically turns your Scala code into a standalone binary. But here is the catch—GraalVM operates on a "Closed World Assumption." It needs to know every single class and method that will ever be touched at runtime during the compilation phase. If it can't see a path to a piece of code, it throws it away to save space.

This is where most of us hit a wall. I remember the first time I tried to move a production service to a native image; it compiled perfectly, but the moment I ran it, the whole thing exploded. Let's look at a snippet that demonstrates exactly why this happens.

case class User(name: String, age: Int)

object NativeDemo {
  def main(args: Array[String]): Unit = {
    // Imagine this class name comes from a config file
    val className = "User" 
    
    println("Attempting to load class reflectively...")
    val clazz = Class.forName(className) 
    println(s"Successfully loaded: ${clazz.getSimpleName}")
  }
}

The Runtime Crash: ClassNotFoundException

If you run this on a standard JVM, it works flawlessly. The JVM is dynamic; it just looks at the classpath at runtime and finds the User class. However, when you compile this with native-image, you'll get a runtime crash that looks something like this:

java.lang.ClassNotFoundException: User
    at java.lang.Class.forName0(Native Image)
    at java.lang.Class.forName(Native Image)
    at NativeDemo.main(NativeDemo.scala:7)

Why? Because GraalVM's static analysis looked at your main method and saw Class.forName(className). Since className is a variable (a string), the compiler has no way of knowing which class you're actually talking about. It looks at the User case class and thinks, "Nothing in the code ever explicitly calls a constructor or a method on User, so I'll just strip it out of the binary to keep the file size small."

Teaching GraalVM about Reflection via JSON

To fix this, we have to explicitly tell GraalVM: "Hey, I know it looks like I'm not using the User class, but I'm going to access it via reflection at runtime. Please keep it."

The most reliable way to do this is by creating a reflect-config.json file. You place this file in your META-INF/native-image directory. Here is what the configuration for our broken example needs to look like:

[
  {
    "name": "User",
    "allDeclaredFields": true,
    "allPublicMethods": true,
    "allDeclaredConstructors": true
  }
]

When you rebuild the native image, GraalVM reads this JSON and adds User to the "keep" list. Now, when Class.forName("User") is called, the class is actually there in the binary, and the program succeeds. I'll be honest: manually writing these JSON files is a chore, especially for large projects with dozens of case classes. In a real-world scenario, you'd likely use the GraalVM agent, which runs your app on a JVM, watches which classes are accessed reflectively, and generates this JSON for you automatically.

Handling Proxy and Resource Issues

Reflection isn't the only thing that trips people up. If you're using a library that generates proxies (like some older Spring versions or certain Scala decorators) or if you're reading a file from the classpath (like getClass.getResourceAsStream("/config.conf")), GraalVM will likely fail you again.

Just like we did with reflection, you need a proxy-config.json for dynamic proxies and a resource-config.json for classpath resources. If you're loading a config file, your resource-config.json would look like this:

[
  {
    "pattern": "config.conf"
  }
]

Without this, the file is simply not bundled into the binary, and your app will return null when trying to find the resource, leading to those dreaded NullPointerExceptions that only happen in the native build.




📋 Practical Task

Exercise: Fixing a Broken Native Config Loader

You have been handed a small Scala project that is supposed to load a system property using reflection to determine which "Environment" class to instantiate. The code works on the JVM, but crashes as a GraalVM Native Image.

The Code:

case class DevEnv(name: String)
case class ProdEnv(name: String)

object EnvLoader {
  def main(args: Array[String]): Unit = {
    val envType = sys.props.getOrElse("env", "DevEnv")
    val clazz = Class.forName(envType)
    println(s"Running in ${clazz.getSimpleName} mode")
  }
}

Your Task:

  1. Create the reflect-config.json file required to make this application work as a native image.
  2. Ensure that both DevEnv and ProdEnv are preserved by the static analyzer.
  3. Specify that the public methods and constructors for these classes must be accessible.

Expected Output: Provide the exact JSON content that would go into reflect-config.json to prevent the ClassNotFoundException for both environment types.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.