Null pointer exception when using java compiler API

MyClass. java:

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

Lists the methods used to compile MyClass Simplecompiletest. Java file java.

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,fileToCompile);
        if(compilationResult == 0){
            System.out.println("Compilation is successful");
        }else{
            System.out.println("Compilation Failed");
        }
    }
}

I'm executing the simplecompiletest class and getting NullPointerException ToolProvider. Getsystemjavacompiler() returned null Can someone tell me what's wrong with the code?

Solution

I suspect you're running this problem - use JRE to run code instead of JDK

When you run simplecompiletest, try adding the Java. Net file you are using The version of exe is explicitly specified as the version in the JDK directory

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>