在运行时编译动态生成的类,而无需写入文件 [英] Compile dynamically generated class at runtime w/o writing to File
问题描述
我正在使用JCodeModel生成Java源代码,现在想在运行时进行编译。但是我不想以前将Java文件写入光盘。
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.
据我所知,可以使用javax.tools.JavaCompiler(< a href = http://www.accordess.com/wpblog/an-overview-of-java-compilation-api-jsr-199/ rel = nofollow>请参见示例),但看起来
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.
不幸的是,我找不到直接从JDefinedClass获取源代码的方法。似乎我需要将JDefinedClass写入磁盘上的File对象,然后再读取源代码。
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?
推荐答案
您可以使用以下代码来避免磁盘操作,并使用 SingleStreamCodeWriter
直接在内存中编写代码:
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
这篇关于在运行时编译动态生成的类,而无需写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!