I am generating a dynamic class in my java program by writing all my code into a java file, compiling the java file into a class file and then loading the class file with a URLClassLoader. The problem with this is that it creates a lot of files on my computer. Is their a way to do this with only creating "virtual files"(file objects) and not generating any actual files, because the way im doing it takes time and seems unclean and inefficient.
If you look at the ClassLoader class, it has a method to define a class from the actual series of bytes.
Java docs for ClassLoader
I admit I have not worked with class loaders on this low of a level, but my understanding is that this is a template pattern, where the base ClassLoader class knows how to create a class in the VM based off raw byte code. Child classes are responsible for figuring out where to find the byte code for a given class.
So the solution for you may be to stop using URLClassLoader entirely and extend ClassLoader yourself.
Byte code generation and manipulation libraries allow you to modify and generate classes on the fly, in memory. Javassist is probably easiest to start with since it permits using Java syntax.
They also tend to be lighter weight than entire standalone compilers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With