我想以编程方式检查java类是否存在编译错误。 你能告诉我怎么做吗?
答案 0 :(得分:4)
您可以使用JavaCompiler API编译该类,它会告诉您是否存在编译错误。
Contrived example(使用字符串作为输入,但您可以读取文件):
String className = "somepackage.YourClass";
String body = "package somepackage; "
+ "public class YourClass { "
+ "} ";
compile(className, body, TEMP_PATH); //TEMP_PATH: Where the .class file is saved
编译可能如下所示:
private static void compile(String className, String body, Path path) throws Exception {
List<JavaSourceFromString> sourceCode = Arrays.asList(new JavaSourceFromString(className, body));
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(path.toFile()));
boolean ok = compiler.getTask(null, fileManager, null, null, null, sourceCode).call();
System.out.println("compilation ok = " + ok);
}
答案 1 :(得分:1)
来自how-do-i-programmatically-compile-and-instantiate-a-java-class
您需要先编译它。这可以使用javax.tools API以编程方式完成。这只需要在JRE顶部的本地计算机上安装JDK。