有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javajavax。工具。JavaCompiler如何捕获编译错误

我想在运行时编译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");
    }
}

测试类。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不会抛出任何异常。它将错误直接打印到控制台中。有没有办法得到字符串格式的编译错误


共 (1) 个答案

  1. # 1 楼答案

    最好的解决方案是使用自己的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
        }