我找到并修改了下面的代码以编程方式编译一个 Java 类:
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class CompileHello {
public static void main(String[] args) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null , null , "C:\\Users\\quickCoder\\Desktop\\Hello.java");
System.out.println("Compile result code = " + result);
}
}
但是,我不断收到以下错误:
Exception in thread "main" java.lang.NullPointerException
at CompileHello.main(CompileHello.java:8)
第 8 行
是下面一行:
int result = compiler.run(null, null , null , "C:\\Users\\quickCoder\\Desktop\\Hello.java");
我确保输入的文件路径是我编写的 Java 类的实际路径。
最佳答案
我怀疑问题是“编译器”在您的 Eclipse 环境中返回为“空”,但在您的 NetBeans 环境中返回非空。
注意:
http://blog.nobel-joergensen.com/2008/07/16/using-eclipse-compiler-to-create-dynamic-java-objects-2/
However to gain access to the JDK compiler you need to run your application from the JDK, and since this is not default behaviour, I choose to use the Eclipse compiler instaid. (Besides the Eclipse compiler share the same interface, so the two compilers should behave similar).
同一链接讨论了如果要在 Eclipse 环境中运行,如何指定使用 Eclipse 编译器。
但是,您可以指向任何 JDK:
How to set classpath when I use javax.tools.JavaCompiler compile the source?
关于java - 以编程方式编译 Java 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31977879/