Java code compilation using JavaCompiler API and compilation errors handling

守給你的承諾、 提交于 2019-12-09 01:38:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!