javacompiler-errorsjarcompilationjava-compiler-api

JavaCompiler, StandardJavaFileManager throws NPE


I want to compile a class from another class but every method I used throws a NullPointerException.

Here's the code:

File fRun = new File(fileToRun);    
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
// NPE IN NEXT LINE
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
Iterable<? extends JavaFileObject> compUnits = fileManager.getJavaFileObjects(fRun);
compiler.getTask(null, fileManager, null, null, null, compUnits).call();            
fileManager.close();

or

public static void main(String[] args) {
    String fileToCompile = "test" + java.io.File.separator + "MyClass.java";
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    // NPE IN NEXT LINE
    int compilationResult = compiler.run(null, null, null, fileToCompile);
    if (compilationResult == 0) {
        System.out.println("Compilation is successful");
    } else {
        System.out.println("Compilation Failed");
    }
}

from http://www.javabeat.net/articles/73-the-java-60-compiler-api-1.html

I start the program from Eclipse.

Wheres the mistake?


Solution

  • Most likely getSystemJavaCompiler() returns null because there is no Java compiler provided on the platform you are running this on. Are you running your program with JDK or with JRE?