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

北城以北 提交于 2019-12-11 00:55:37

问题


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


来源:https://stackoverflow.com/questions/13608290/compile-dynamically-generated-class-at-runtime-w-o-writing-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!