Java – Compiles dynamically generated classes at runtime without writing to a file

Compiles dynamically generated classes at runtime without writing to a file… here is a solution to the problem.

Compiles dynamically generated classes at runtime without writing to a file

I am using JCodeModel to generate java source code and now want to compile at runtime. But I didn’t want to write Java files to CD.

As far as I know, you can use javax.tools.JavaCompiler ( see example) to compile dynamically, but it looks like I need the source code for it.

Unfortunately, I couldn’t find a way to get the source code directly from JDefinedClass. It’s as if I need to write JDefinedClass to a File object on the disc and then read the source code.

Is this really necessary or is there some workaround?

Solution

You can use the following code to avoid disk operations and use SingleStreamCodeWriter to write code directly to memory:

JCodeModel jCodeModel = createJCodeModel();  create and prepare JCodeModel 
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CodeWriter codeWriter = new SingleStreamCodeWriter(baos);
jCodeModel.build(codeWriter);

String code = baos.toString();  you can use toString(charset) if there are special characters in your code

Related Problems and Solutions