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

时间:2015-10-16 14:20:05

标签: 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块:

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

这不起作用,因为JavaCompiler不会抛出任何异常。它将错误直接打印到控制台。是否有任何方式以String格式获取编译错误?

1 个答案:

答案 0 :(得分:1)

最好的解决方案是使用自己的OutputStream,它将用于代替console:

 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
    }