The generation of classes at runtime is an advanced topic that requires a lot of knowledge that can be reduced if you use particular libraries that perform the most complex functions to accomplish this task.
So, for this purpose, we can use the ClassFactory component and the sources generating components of the Burningwave Core library by adding to our pom.xml the following dependency:
After this we set the code to be generated in UnitSourceGenerator objects and we must pass it to loadOrBuildAndDefine method of ClassFactory with the ClassLoader where you want to define newly generated classes.
This method performs the following operations: tries to load all the classes present in the UnitSourceGenerator through the class loader, if at least one of these is not found it proceeds to compile all the UnitSourceGenerators and uploading their classes on class loader: in this case, keep in mind that if a class with the same name was previously loaded by the class loader, the compiled class will not be uploaded. If you need more information you can:
- see a complete example about source code generators
- read this guide where you also can find a link to an example about generating classes by using libraries located outside the runtime class paths
- go here for more examples
- ask for assistance at the official forum (topic "How to do?")
- ask Stack Overflow for assistance
Once the classes have been compiled and loaded, it is possible to invoke their methods in severals ways as shown at the end of the example below.
In this short article we have learned how to generate classes at runtime in Java, how to load them and create instances; the complete source is available at this at this page.