NullPointerException when trying to get Java compiler instance

2

Next, I'm trying to get a Java compiler instance through the following code:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

if (compiler == null) {
    System.out.println("No compiler");
    return;
}

The problem is that it always falls into if, and I can not understand why.

I want to know what I'm doing wrong.

    
asked by anonymous 05.10.2016 / 00:43

1 answer

2

This problem occurs when you run the code with a JRE and not a JDK. To resolve, you must enter the JDK path in the java.home property. One way to do this programmatically is by directly reporting the value of the property in the system:

System.setProperty("java.home", "caminho_do_java");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

if (compiler == null) {
    System.out.println("No compiler");
    return;
}

Replace string caminho_do_java with the path of your JDK.

    
05.10.2016 / 01:51