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); |