问题
I have the following Java code that compiles the given Java code using the javax.tools.JavaCompiler API:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
ByteArrayOutputStream err = new ByteArrayOutputStream();
compiler.run(new FileInputStream("Test.java"),
new FileOutputStream("Test.class"),
err,
"Test.java"); // Test.java contains the code of a simple Java class
String compilationErrors = err.toString();
In the above code, all compilation errors are returned as one String instance.
Is there a way to get compilation errors parsed i.d. get the file name, line number, cause of the error and line of code or do I have to do the parsing?
回答1:
According to my understanding of JavaCompiler.getTask(..) I'd suggest adding a DiagnosticListener. It seems to provide all the details needed.
This is the code I have been looking for:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.
getStandardFileManager(diagnostics, null, null);
Iterable<? extends JavaFileObject> compilationUnits = fileManager.
getJavaFileObjectsFromFiles(Arrays.asList(new File("Test.java")));
CompilationTask task = compiler.getTask(null, fileManager, diagnostics,
null, null, compilationUnits);
task.call();
for(Diagnostic<?> error : diagnostics.getDiagnostics()) {
//
}
来源:https://stackoverflow.com/questions/20771737/java-code-compilation-using-javacompiler-api-and-compilation-errors-handling