Run-Time Class Loading

Native Image provides experimental support for loading classes dynamically at run time. When enabled, a class loader can define classes from bytecode through ClassLoader.defineClass. This feature opens Native Image’s type world, makes Class.forName respect its class-loader argument.

Usage

Enable the feature with the -H:+RuntimeClassLoading build option. Because this is an experimental option, unlock experimental VM options for the build:

native-image -H:+UnlockExperimentalVMOptions -H:+RuntimeClassLoading -H:-UnlockExperimentalVMOptions -jar app.jar app
./app

Use run-time class loading when an application or library defines classes from bytecode after the executable starts. This is useful when generated bytecode is not available at build time or varies between initializations, as can happen with generated proxies.

Limitations

The JVM identifies each class by its defining class loader and binary name. A class loader cannot define the same binary name twice, so define variants with different class loaders or different names.

Run-time-loaded classes can link to build-time-loaded classes, but analysis may remove methods or static fields from those classes. Use -H:Preserve=package=... at build time to retain all methods and fields in a package when needed.

Parallel class loading is not supported. URLClassLoader and loading classes from the JDK or application class loader may require additional setup.

Enabling run-time class loading may increase the image size and memory usage.

Also, it cannot be combined with predefined-classes.

While -H:+RuntimeClassLoading is sufficient to allow defineClass to work, extra setup may be needed depending on the specific use case. See the run-time class loading guide for examples. For a working example, see the dynamic class loading demo.

Connect with us