使用Java Compiler API时出现空指针异常 [英] Null Pointer Exception while using Java Compiler API

查看:453
本文介绍了使用Java Compiler API时出现空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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时出现空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆