Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile dynamically generated class at runtime w/o writing to File

I'm generating java sources with JCodeModel and now want to compile at runtime. But I don't want to write the Java files to disc before.

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

Unfortunately I can't find a way to directly get the source code from a JDefinedClass. It seems as if I need to write a JDefinedClass to a File object on disc and read the source afterwards.

Is this really necessary or is there some workaround?

like image 322
Morrandir Avatar asked Apr 22 '26 21:04

Morrandir


1 Answers

You can use following code to avoid disk operations and write your code directly in memory using 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
like image 116
hoaz Avatar answered Apr 24 '26 10:04

hoaz