import java.io.*; import java.util.*; import javax.tools.*;
public class test_compilerapi { private static void compilejava() throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); // 建立DiagnosticCollector对象 DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); // 建立用于保存被编译文件名的对象 // 每个文件被保存在一个从JavaFileObject继承的类中 Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjectsFromStrings(Arrays asList("test3.java")); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits); // 编译源程序 boolean success = task.call(); fileManager.close(); System.out.println((success)?"编译成功":"编译失败"); } public static void main(String args[]) throws Exception { compilejava(); } } |