代码案例:
import java.util.ArrayList;
import java.util.List;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class JDK6CompileUtil {
/**
* 编译
*/
public static void compiler(){
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int results = compiler.run(null, null, null, "C:\\Test.java");
System.out.println("Success: " + (results == 0));
}
/**
* 编译
*
* @throws Exception
*/
public static void compiler2()throws Exception{
List list = new ArrayList();
list.add("C:\\Test.java");
list.add("C:\\Test2.java");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector diagnostics = new DiagnosticCollector();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
Iterable extends JavaFileObject> compilationUnits = fileManager
.getJavaFileObjectsFromStrings(list);
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null,
null, compilationUnits);
boolean success = task.call();
fileManager.close();
System.out.println("Success: " + success);
}
/**
* @param args
*/
public static void main(String[] args) {
try {
compiler2();
} catch (Exception e) {
e.printStackTrace();
}
}
}