CompilerUtil.md

Introduction

JDK provides JavaCompiler for dynamically compiling Java source code files, which can then be loaded by a class loader. This dynamic compilation allows Java to have the characteristics of a dynamic scripting language, and Hutool encapsulates the corresponding tools for this purpose.

Usage

First, we will package the class files and jar files that the compilation depends on:

// Depend on A, compile B and C
final File libFile = ZipUtil.zip(FileUtil.file("lib.jar"),
 new String[]{"a/A.class", "a/A$1.class", "a/A$InnerClass.class"},
 new InputStream[]{
 FileUtil.getInputStream("test-compile/a/A.class"),
 FileUtil.getInputStream("test-compile/a/A$1.class"),
 FileUtil.getInputStream("test-compile/a/A$InnerClass.class")
 });

Start compiling:

final ClassLoader classLoader = CompilerUtil.getCompiler(null)
 // The source code file to be compiled
 .addSource(FileUtil.file("test-compile/b/B.java"))
 // The source code string to be compiled
 .addSource("c.C", FileUtil.readUtf8String("test-compile/c/C.java"))
 // The libraries that the compilation depends on
 .addLibrary(libFile)
 .compile();

Load the compiled class:

final Class<?> clazz = classLoader.loadClass("c.C");
// Instantiate object c
Object obj = ReflectUtil.newInstance(clazz);