Compile dynamically generated class at runtime without writing to file

I am generating java sources using JCodeModel and now want to compile at runtime. But I don't want to write Java files to disk before.

As far as I can tell, dynamic compilation is possible with javax.tools.JavaCompiler ( see example ), but it looks like I need the source code for that.

Unfortunately, I cannot find a way to get the source code from the JDefinedClass directly. It seems I need to write a JDefinedClass for the File object on disk and read the source code afterwards.

Is this really necessary or is there some workaround?

+1


source to share


1 answer


You can use the following code to avoid disk operations and write your code directly in memory with SingleStreamCodeWriter

:



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

      

+1


source







All Articles