使用JavaCompilerAPI编译Java代码和编译错误处理

使用JavaCompilerAPI编译Java代码和编译错误处理,java,compilation,Java,Compilation,我有以下Java代码,它使用javax.tools.JavaCompilerAPI编译给定的Java代码: JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); ByteArrayOutputStream err = new ByteArrayOutputStream(); compiler.run(new FileInputStream("Test.java"), new FileOutputStream("Tes

我有以下Java代码,它使用
javax.tools.JavaCompiler
API编译给定的Java代码:

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();
在上面的代码中,所有编译错误都作为一个
String
实例返回


是否有办法解析编译错误ID。获取文件名、行号、错误原因和代码行,或者我必须进行解析?

根据我对的理解,我建议添加一个。它似乎提供了所需的所有细节


这是我一直在寻找的代码:

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()) {
    // 
}
JavaCompiler compiler=ToolProvider.getSystemJavaCompiler();
诊断收集器诊断=
新诊断收集器();
StandardJavaFileManager文件管理器=编译器。
getStandardFileManager(诊断、空、空);

IterableThanks,这似乎正是我想要的。我会试试看。