0

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?

Lindstorm
  • 890
  • 2
  • 7
  • 22
  • 1
    Where should the java compiler come from? Do you have any kind of JAR file in your classpath you can use? – Progman Sep 25 '20 at 16:01
  • You could try to get the path and of the JDK of another version and execute `javac` or run a program there manually. You may also be able to use `-release`. – dan1st Sep 25 '20 at 16:07
  • @Progman It could come from anywhere. In reality, the compilers would be in src/main/resources, and then I do something with that, or there is some library function that has a `SourceVersion` parameter and returns a `JavaCompiler` instance. I don't know of a jar on my classpath because of the tools.jar being removed since Java 9 – Lindstorm Sep 25 '20 at 16:08
  • Are you asking how to use a piece of software without having the software? The answer is that you need to have the version of Java on the computer that you want to use that version of Java on. – kaya3 Sep 25 '20 at 16:19
  • @kaya3 That is not what I am asking at all. I am asking how to use `JavaCompiler` API for Java versions other than the one on your path – Lindstorm Sep 25 '20 at 16:34

0 Answers0