javax.tools.JavaCompiler如何捕获编译错误

标签 java

我想在运行时编译Java类。假设该文件如下所示:

public class TestClass
{
    public void foo()
    {
        //Made error for complpilation
        System.ouuuuut.println("Foo");
    }
}

该文件 TestClass.java 位于 C:\

现在我有一个编译此文件的类:

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

class CompilerError
{
    public static void main(String[] args)
    {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        compiler.run(null, null, null, "C:\\TestClass.java");
    }
}

TestClass.java 的方法名称不正确,因此无法编译。在控制台中显示:

C:\TestClass.java:7: error: cannot find symbol
        System.ouuuuut.println("Foo");
              ^
  symbol:   variable ouuuuut
  location: class System
1 error

这正是我所需要的,但我需要它作为字符串。如果我尝试使用 try/catch block :

try
        {
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            compiler.run(null, null, null, "C:\\TestClass.java");
        } catch (Throwable e){
            e.printStackTrace(); //or get it as String
        }

这不会起作用,因为 JavaCompiler 不会抛出任何异常。它将错误直接打印到控制台。有什么方法可以得到字符串格式的编译错误吗?

最佳答案

最好的解决方案是使用自己的OutputStream,它将代替控制台使用:

 public static void main(String[] args) {

        /*
         * We create our own OutputStream, which simply writes error into String
         */

        OutputStream output = new OutputStream() {
            private StringBuilder sb = new StringBuilder();

            @Override
            public void write(int b) throws IOException {
                this.sb.append((char) b);
            }

            @Override
            public String toString() {
                return this.sb.toString();
            }
        };

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        /*
         * The third argument is OutputStream err, where we use our output object
         */
        compiler.run(null, null, output, "C:\\TestClass.java");

        String error = output.toString(); //Compile error get written into String
    }

关于javax.tools.JavaCompiler如何捕获编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33172771/

相关文章:

java - 如何让 Shell 在 SWT 中始终处于最前面?

java - Android 应用程序因 RuntimeException : Unable to instantiate activity, dident find 类而崩溃

java - hive : How to flatten an array?

java - Hibernate Criteria 按子记录数排序

java - 可用的最大套接字连接数

java - 无法让我的对象加载器工作

java - 我如何/可以使用 base64 作为 Jasper 报告模板中的图像源?

java - 对象方法不能访问对象变量吗?

java - 如何取消AlarmManager中设置的所有闹钟?

java - "return"是否停止了方法的执行?