Running the Java Compiler from a JUnit test is pretty simple using the Java Compiler API. The test checks that I can load new code using a temporary classloader and that the cleanup works, etc
My problem is compiling and/or running the test using Maven.
If I add the java compiler using a dependency, I must set the scope to test. If I do that, the tools.jar will be added to the classpath when the tests are being compiled which means that there will be two Java compilers on the classpath.
The same is true for the scope runtime but that will also add the Java compiler to my artifact, making it leak. All other scopes are even worse.
How can I solve this?
Are you sure that you need the java compiler dependency at all? Without any special (compiler) dependency the Java Compiler API works for me (as it’s part of the JDK).
You can set the target VM version with the
optionsparameter ofgetTask, for example: