11

MyClass.java:

package test;
public class MyClass {
    public void myMethod(){
        System.out.println("My Method Called");
    }
}

编译 MyClass.java 文件的 SimpleCompileTest.java 的清单。

简单编译测试.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。有人可以告诉我代码有什么问题吗

4

6 回答 6

18

我得到了同样的错误。也许我回答这个问题为时已晚,但我分享我自己的经验,它可能会帮助其他人在未来面临同样的问题。我在Compile Java Files At Runtime上玩弄源代码。

我得到java.lang.NullPointerException了它所提到的。我用 打印出 Java 主目录System.out.println(System.getProperty("java.home"));,并注意到我的 Eclipse 指向“ C:\Program Files\Java\jre7”,即使我将偏好更改为使用 JDK1.7 而不是 JRE1.7。

我通过设置这样的系统属性来强制使用 JDK1.7 找到了一种解决方法:

System.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.7.0_02");

然后我编译了我的程序并没有得到任何NullPointerException.

于 2012-06-08T07:40:00.353 回答
16

我怀疑您遇到了这个问题- 使用 JRE 而不是 JDK 运行代码。

运行时SimpleCompileTest,尝试明确指定您使用的 java.exe 版本作为 JDK 目录中的版本。

于 2010-03-30T07:30:30.237 回答
1

可能您安装了 JRE 而不是 JDK。http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6477844

于 2010-03-30T07:30:44.213 回答
1

我遇到了同样的问题

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

正在返回 null。即使在使用后

System.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.8.0_31");

正在返回 null。

However the issue was simple as this code is in the Tools.jar found in Java\jdk1.8.0_31\lib if you are using JDK. what i did was to go to project-->properties-->Java Build Path-->order and export--> and moved tool.jar to the top of other JRE and projects. This helped me get rid of null hope this help you as well.Happy compiling...:-)

于 2015-03-10T12:12:04.033 回答
0

它通过明确包含 tools.jar 与 Java 应用程序一起使用,但对于 Web 应用程序不起作用。抛出空指针

于 2012-02-29T10:30:42.040 回答
0

补充:上面的答案是在程序中设置 java.home 系统属性。这也适用于我,但这不是一个非常通用的解决方案,因为您已经为一个 jdk 版本进行了硬编码。我现在使用的替代方法是在运行程序时在命令行上提供“java”的完整路径。如(与上面的例子一致):

C:\\Program Files\Java\jdk1.7.0_02\jre\bin\java -cp ..\classes path.to.program.myProgram

给出 jdk 版本的完整路径意味着这是运行程序的版本,所以这就是将使用 ToolProvider.getSystemJavaCompiler() 获取的版本;

于 2014-08-22T15:20:50.283 回答