javaclasscompilationjvmruntime-environment

Compile Java source files against running JVM from within Java


Compiling Java source code from within java is a task that is aided by the Java Compiler Tools within the javafx.tools package. However there is something I can't seem to find any information about.

The question I ask is if it's possible to compile the java files against the JVM being used to compile it. I am writing code that runs on software that makes use of several jar libraries, some of them quite large, and I intend to dynamically compile individual java files and load the resulting class files to operate almost like a scripting language. In order for the compiled java files to access classes and variables within the software, it needs to have all the same libraries added to its classpath upon building, or I'll face compilation errors.

I've searched around for information on whether this is impossible or not, and can't find it, I get completely irrelevant results.

If it is impossible I could link all needed libraries (over 30 of them), I would just prefer not to. If it is impossible to compile against the current environment, then what would you consider the easiest way to dynamically get a list of all libraries being loaded in the JVM are?

Edit: In response to Jim, I understand that java files are compiled into class files and that class files are the ones loaded. I understand that libraries need to be accessible to the compiler, etc. What I'm stating is the fact that I have over 30 libraries totaling over 380 MB, and I have a couple hundred individual java source files in a folder that extend a class defined within the main program to be used as a module, If I have to link all several hundred of them with 380 MB of files for compiling, that's a lot of time taken. I could compile them all together to fix most of the problem, but the main issue is that the list of files to run are added in the -classpath argument of the command line, and this can change at any time, so I can not hard code this. That's why the second part of the question exists, how would I get the classpath being used to run the current program so that I can then pass it into the compiler.


Solution

  • When you use the Compiler API, you specify the ClassLoader you want to use. This ClassLoader then provides all the classes you might need to compile your code. I can't remember the details but I wrote a library for in memory compilation of Java code about 5 years ago. https://github.com/OpenHFT/Java-Runtime-Compiler