How do you create a JavaCompiler instance for a JDK not on your path?

111 views Asked by At

How do you create a JavaCompiler instance not on your system? More specifically, I would like to be able to create a JavaCompiler instance from a version number.

The only techniques I have seen for creating JavaCompiler instances are

  • Using JavaCompiler compiler = ToolProvider.getSystemJavaCompiler().

  • Using JavaCompiler compiler = new JavacTool()

  • Locate the tools.jar file for the compiler, and then use the following code. The problem with this is the tools.jar has been removed since JDK 9

     File file = new File(pathToToolsJar);
     URL[] urls = new URL[]{ file.toURI().toURL() };
     ClassLoader loader = new URLClassLoader(urls);
     Class compilerClass = loader.loadClass("com.sun.tools.javac.api.JavacTool");
     JavaCompiler compiler = (JavaCompiler) compilerClass.getConstructor().newInstance();
    

Is there anyway to create a JavaCompiler instance for any Java version?

0

There are 0 answers