我有以下Java代码使用 javax.tools.JavaCompiler API编译给定的Java代码:
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();在上面的代码中,所有编译错误都返回为 String 实例。
In the above code, all compilation errors are returned as one String instance.
有一种方法可以解析i.d.的编译错误。
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?
推荐答案如何获取文件名,行号,错误原因和代码行?根据我对 JavaCompiler.getTask 我建议您添加 DiagnosticListener 。似乎提供了所需的所有细节。
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()) { // }更多推荐
使用JavaCompiler API进行Java代码编译和编译错误处理
发布评论