我想在运行时编译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/