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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With