Nullpointerexception when trying to obtain Java compiler instance

Asked

Viewed 47 times

2

Next, I’m trying to get an instance of the Java compiler, using the following code:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

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

The problem is that it always falls inside the if, and I can’t understand why.

I want to know what I’m doing wrong.

1 answer

2


This problem occurs when you run the code with a JRE and not a JDK. To solve, you need to inform the JDK path in the property java.home. One way to do this programmatically is to directly inform 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 the string caminho_do_java by the way of your JDK.

  • 1

    What is the property java.home?

  • 1

    https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

  • It would be interesting to add the link in the response, directed from "java.home", so if someone reads and does not understand, just click on the link to check.

  • @Giulianabezerra I had already tried this, but I got the following java.lang.Internalerror: java.io.Filenotfoundexception: C: Program Files Java jdk1.8.0_101 lib currency.data (The system cannot find the specified file)

  • @Giulianabezerra I managed to settle the way you said, but after setting the property java.home for jdk and get the compiler instance, set back to jre, which solved the problem I mentioned above. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.