Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null Pointer Exception while using Java Compiler API

MyClass.java:

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

Listing for SimpleCompileTest.java that compiles the MyClass.java file.

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");
        }
    }
}

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

like image 250
java_geek Avatar asked Mar 30 '10 07:03

java_geek


3 Answers

I got the same error. Maybe I am too late to answer this question, but I share my own experiences, it might help someone else facing the same issue in the future. I was playing around with the source code at Compile Java Files At Runtime.

I was getting java.lang.NullPointerException as it is mentioned. I printed out the Java home directory with System.out.println(System.getProperty("java.home"));, and noticed my Eclipse was pointing to "C:\Program Files\Java\jre7" even after I changed my preferences to use JDK1.7 instead of JRE1.7.

I found a workaround by forcing the usage of JDK1.7 by setting system property like this:

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

Then I compiled my program and did not get any NullPointerException.

like image 61
rashid Avatar answered Oct 14 '22 02:10

rashid


I suspect you're running into this problem - running the code with a JRE instead of a JDK.

When you run SimpleCompileTest, try explicitly specifying the version of java.exe you're using as the one in your JDK directory.

like image 16
Jon Skeet Avatar answered Oct 14 '22 01:10

Jon Skeet


Probably you have a JRE instead of JDK installed. http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6477844

like image 1
stacker Avatar answered Oct 14 '22 03:10

stacker