How to generate and compile sources at runtime in Java

With ClassFactory it is possible to generate classes at runtime, but how we can do if we only need to compile sources without loading them or just generate sources?

Here they come to our aid the source code generator components and the JavaMemoryCompiler of Burningwave Core. With source code generators we can generate source code and store it on the drive or compile it via the JavaMemoryCompiler.

To use all these components you should simply add the following to your projects dependencies:

Now we are going to generate and store the following class:

… With the following source code generators:

And now let’s try to load the compiled file:

Conclusion

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 which are not mentioned here like, for example, compile sources that references classes located outside the runtime class paths and if you are curious or need further help you can request it at the official forum and for more articles about Burningwave Core you can go to the main page.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store