使用JavaCompiler API进行Java代码编译和编译错误处理

编程入门 行业动态 更新时间:2024-10-26 10:41:02
本文介绍了使用JavaCompiler API进行Java代码编译和编译错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下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代码编译和编译错误处理

本文发布于:2023-11-25 17:28:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   代码   JavaCompiler   API   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!