How to Generate and Compile Sources at Runtime in Java
In this article, learn how to generate and compile sources at runtime in Java with and without class loading.
Join the DZone community and get the full member experience.Join For Free
With ClassFactory, it is possible to generate classes at runtime, but how can we do that if we only need to compile sources without loading them or just generating sources?
Here come the source code generator components and the JavaMemoryCompiler of Burningwave Core to our aid. With source code generators, we can generate source code and store it on the drive or compile it via the JavaMemoryCompiler.
Now, let's try to generate and store the following class:
With the source code generators:
And now let's try to compile the sources and store the compiled files with JavaMemoryCompiler:
And now let's try to load the compiled file:
In this tutorial, we learned how to generate and compile sources and how to load the generated class files. You can do a lot of things that are not mentioned here like, for example, compile sources that references classes located outside the runtime class paths. If you are curious or need further help, you can request it at the official forum.
Opinions expressed by DZone contributors are their own.