Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Dynamic Class Java

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.

like image 234
Josh Sobel Avatar asked Nov 03 '22 02:11

Josh Sobel


2 Answers

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.

like image 161
Brandon Avatar answered Nov 15 '22 09:11

Brandon


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.

like image 45
Joni Avatar answered Nov 15 '22 10:11

Joni