核心对象:1 JavaCompiler 2 StandardJavaFilemanager
1、初始化JavaCompiler:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
2、初始化StandardFilemanager
this.stdManager = compiler.getStandardFileManager(null, null, null);
3 编写核心方法:
/**
* Compile a Java source file in memory.
*
* @param fileName
* Java file name, e.g. "Test.java"
* @param source
* The source code as String.
* @return The compiled results as Map that contains class name as key,
* class binary as value.
* @throws IOException
* If compile error.
*/
public Map<String, byte[]> compile(String fileName, String source) throws IOException {
try (MemoryJavaFileManager manager = new MemoryJavaFileManager(stdManager)) {
JavaFileObject javaFileObject = manager.makeStringSource(fileName, source);
CompilationTask task = compiler.getTask(null, manager, null, null, null, Arrays.asList(javaFileObject));
Boolean result = task.call();
if (result == null || !result.booleanValue()) {
throw new RuntimeException("Compilation failed.");
}
return manager.getClassBytes();
}
}