在很多Java应用中需要在程序中调用Java编译器来编译和运行。但在早期的版本中(Java SE5及以前版本)中只能通过tools.jar中的com.sun.tools.javac包来调用Java编译器,但由于tools.jar不是标准的Java库,在使用时必须要设置这个jar的路径。而在Java SE6中为我们提供了标准的包来操作Java编译器,这就是javax.tools包。使用这个包,我们可以不用将jar文件路径添加到classpath中了。
一、使用JavaCompiler接口来编译Java源程序
使用Java API来编译Java源程序有很多方法,现在让我们来看一种最简单的方法,通过JavaCompiler进行编译。
我们可以通过ToolProvider类的静态方法getSystemJavaCompiler来得到一个JavaCompiler接口的实例。
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); |
int run(InputStream in, OutputStream out, OutputStream err, String... arguments) |
int results = tool.run(null, null, null, "test.java"); |
import java.io.*; import javax.tools.*; public class test_compilerapi { public static void main(String args[]) throws IOException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); int results = compiler.run(null, null, null, "test.java"); System.out.println((results == 0)?"编译成功":"编译失败"); // 在程序中运行test Runtime run = Runtime.getRuntime(); Process p = run.exec("java test"); BufferedInputStream in = new BufferedInputStream(p.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s; while ((s = br.readLine()) != null) System.out.println(s); } } public class test { public static void main(String[] args) throws Exception { System.out.println("JavaCompiler测试成功!"); } } |
test.java:9: 找不到符号 符号: 方法 printlnln(java.lang.String) 位置: 类 java.io.PrintStream System.out.printlnln("JavaCompiler测试成功!"); ^ 1 错误 编译失败 |
getTask(Writer out,JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits) |
Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles( Iterable<? extends File> files) Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings( Iterable<String> names) String[] filenames = …; Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(filenames)); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits); |
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(); } } |
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) System.out.printf( "Code: %s%n" + "Kind: %s%n" + "Position: %s%n" + "Start Position: %s%n" + "End Position: %s%n" + "Source: %s%n" + "Message: %s%n", diagnostic.getCode(), diagnostic.getKind(), diagnostic.getPosition(), diagnostic.getStartPosition(), diagnostic.getEndPosition(), diagnostic.getSource(), diagnostic.getMessage(null)); |
public class test { public static void main(String[] args) throws Exception { aa; //错误语句 System.out.println("JavaCompiler测试成功!"); } } |
Code: compiler.err.not.stmt Kind: ERROR Position: 89 Start Position: 89 End Position: 89 Source: test.java Message: test.java:5: 不是语句 Success: false |
Iterable<String> options = Arrays.asList("-d", "d:\\"); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits); |
import java.lang.reflect.*; import java.io.*; import javax.tools.*; import javax.tools.JavaCompiler.CompilationTask; import java.util.*; import java.net.*; public class test_compilerapi { private static void compilerJava() throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); // 定义一个StringWriter类,用于写Java程序 StringWriter writer = new StringWriter(); PrintWriter out = new PrintWriter(writer); // 开始写Java程序 out.println("public class HelloWorld {"); out.println(" public static void main(String args[]) {"); out.println(" System.out.println(\"Hello, World\");"); out.println(" }"); out.println("}"); out.close(); //为这段代码取个名子:HelloWorld,以便以后使用reflection调用 JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString()); Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file); JavaCompiler.CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits); boolean success = task.call(); System.out.println("Success: " + success); // 如果成功,通过reflection执行这段Java程序 if (success) { System.out.println("-----输出-----"); Class.forName("HelloWorld").getDeclaredMethod("main", new Class[] { String[].class }).invoke(null, new Object[] { null }); System.out.println("-----输出 -----"); } } public static void main(String args[]) throws Exception { compilerJava(); } } // 用于传递源程序的JavaSourceFromString类 class JavaSourceFromString extends SimpleJavaFileObject { final String code; JavaSourceFromString(String name, String code) { super(URI.create("string:///" + name.replace('.', '/')+ Kind.SOURCE.extension), Kind.SOURCE); this.code = code; } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return code; } } |