Compile dynamically generated class at runtime w/o

2019-07-15 02:57发布

问题:

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?

回答1:

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