Backend Development 6 min read

Java Dynamic Compilation and Runtime Hot Reload with JavaCompiler and Custom ClassLoader

By using the JavaCompiler API to compile source files at runtime together with a custom ClassLoader that loads the generated bytecode, developers can hot‑reload changed classes instantly without restarting the JVM, enabling rapid iteration, plugin‑style extensions, and faster development cycles.

Java Tech Enthusiast
Java Tech Enthusiast
Java Tech Enthusiast
Java Dynamic Compilation and Runtime Hot Reload with JavaCompiler and Custom ClassLoader

In traditional Java development, each code change requires recompilation and application restart, which is time‑consuming and hampers rapid iteration. Java dynamic compilation and runtime hot‑load technologies enable immediate effect of code modifications without restarting the JVM.

This article demonstrates how to use the JavaCompiler API to compile Java source code at runtime and a custom ClassLoader to load the newly generated classes, thereby improving development efficiency.

Example of dynamic compilation using JavaCompiler :

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.*;

public class DynamicCompiler {
    public static void main(String[] args) throws Exception {
        String source = "public class HelloWorld { public static void main(String[] args) { System.out.println(\"Hello, Dynamic Compilation!\"); } }";
        File sourceFile = new File("HelloWorld.java");
        try (FileWriter writer = new FileWriter(sourceFile)) {
            writer.write(source);
        }
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        compiler.run(null, null, null, sourceFile.getPath());
        Process process = Runtime.getRuntime().exec("java HelloWorld");
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

After compilation, the program creates HelloWorld.java , compiles it, and executes it.

Runtime hot‑load is achieved by a custom HotReloadClassLoader that reads the compiled class bytes and defines the class dynamically:

import java.io.*;
import java.net.*;

public class HotReloadClassLoader extends ClassLoader {
    private final String classPath;
    public HotReloadClassLoader(String classPath) {
        this.classPath = classPath;
    }
    @Override
    public Class
findClass(String name) throws ClassNotFoundException {
        try {
            byte[] classBytes = loadClassBytes(name);
            return defineClass(name, classBytes, 0, classBytes.length);
        } catch (IOException e) {
            throw new ClassNotFoundException("Failed to load class: " + name, e);
        }
    }
    private byte[] loadClassBytes(String name) throws IOException {
        File classFile = new File(classPath + name.replace('.', '/') + ".class");
        try (FileInputStream fis = new FileInputStream(classFile);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, length);
            }
            return bos.toByteArray();
        }
    }
}

Combining the above DynamicCompiler and HotReloadClassLoader yields a complete instant‑update workflow:

public class HotReloadDemo {
    public static void main(String[] args) throws Exception {
        String classPath = "./";
        HotReloadClassLoader loader = new HotReloadClassLoader(classPath);
        Class
clazz = loader.loadClass("HelloWorld");
        clazz.getMethod("main", String[].class).invoke(null, (Object) new String[]{});
    }
}

Each time HelloWorld.java is modified and recompiled, the new class can be loaded without restarting the application.

Conclusion : By leveraging the JavaCompiler API and a custom ClassLoader , developers can achieve immediate code updates, facilitating rapid testing, plugin‑style architectures, and dynamic script execution, thereby significantly boosting development speed and responsiveness.

JavaruntimeClassLoaderDynamic Compilationhot reloadJavaCompiler
Java Tech Enthusiast
Written by

Java Tech Enthusiast

Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.