问题描述
MyClass.java:
MyClass.java:
package test;
public class MyClass {
public void myMethod(){
System.out.println("My Method Called");
}
}
编译MyClass.java的SimpleCompileTest.java的列表文件。
Listing for SimpleCompileTest.java that compiles the MyClass.java file.
SimpleCompileTest.java:
SimpleCompileTest.java:
package test;
import javax.tools.*;
public class SimpleCompileTest {
public static void main(String[] args) {
String fileToCompile = "test" + java.io.File.separator +"MyClass.java";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null, fileToCompile);
if(compilationResult == 0){
System.out.println("Compilation is successful");
}else{
System.out.println("Compilation Failed");
}
}
}
我正在执行SimpleCompileTest类并获得NullPointerException。 ToolProvider.getSystemJavaCompiler()返回null。有人能告诉我代码有什么问题
I am executing the SimpleCompileTest class and getting a NullPointerException. The ToolProvider.getSystemJavaCompiler() is returning null. Can someone tell me what is wrong with the code
推荐答案
我怀疑你遇到了 - 使用JRE而不是JDK运行代码。
I suspect you're running into this problem - running the code with a JRE instead of a JDK.
当您运行 SimpleCompileTest
时,请尝试显式指定您正在使用的java.exe版本作为JDK中的版本目录。
When you run SimpleCompileTest
, try explicitly specifying the version of java.exe you're using as the one in your JDK directory.
这篇关于使用Java Compiler API时出现空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!