views:

215

answers:

2

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

+2  A: 

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.

Jon Skeet
+1  A: 

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

stacker