JavaCompiler,StandardJavaFileManager抛出NPE

时间:2012-03-08 14:46:37

标签: java compiler-construction compilation jar compiler-errors

我想从另一个类编译一个类,但我使用的每个方法都抛出一个NullPointerException。

以下是代码:

File fRun = new File(fileToRun);    
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
// NPE IN NEXT LINE
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
Iterable<? extends JavaFileObject> compUnits = fileManager.getJavaFileObjects(fRun);
compiler.getTask(null, fileManager, null, null, null, compUnits).call();            
fileManager.close();

public static void main(String[] args) {
    String fileToCompile = "test" + java.io.File.separator + "MyClass.java";
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    // NPE IN NEXT LINE
    int compilationResult = compiler.run(null, null, null, fileToCompile);
    if (compilationResult == 0) {
        System.out.println("Compilation is successful");
    } else {
        System.out.println("Compilation Failed");
    }
}

来自http://www.javabeat.net/articles/73-the-java-60-compiler-api-1.html

我从Eclipse启动程序。

这是错误吗?

2 个答案:

答案 0 :(得分:2)

很可能getSystemJavaCompiler()返回null,因为您运行它的平台上没有提供Java编译器。您是使用JDK还是使用JRE运行程序?

答案 1 :(得分:2)

在您的案例中,compiler变量似乎是null。该文档指出,如果您在没有可用编译器的环境中调用它,则会发生这种情况,例如:只使用JVM而不是JDK安装: http://docs.oracle.com/javase/6/docs/api/javax/tools/ToolProvider.html#getSystemJavaCompiler()

确保使用具有可用编译器的完整JDK运行程序。