我正在重构一个使用 javaCC 在编译期间创建专有语言解析器的项目。由于可以同时存在不同的语言变体,所以决定在运行时从jj文件中动态生成java源代码,然后将java文件编译成class文件并加载。
为了更有效地执行此操作,我想将内存中的 java 文件生成到我想的某个流中。JavaCC 的 API Javadoc 不太容易访问 :)。
如何最好地进步?
You could use the Compiler API aka JSR-199 (see javax.tools
) to compile in memory generated classes. You'll need to extend javax.tools.SimpleJavaFileObject
class to create a class that will represent the source text of a Java class in RAM.
Check out the following example, it has an implementation of a RAMResidentJavaFileObject
that is actually doing that.
您最好按照 kdgregory 的建议修改构建过程。但是,本文描述了如何创建一个新的类加载器,该类加载器使用编译器 API 即时编译 Java 代码。修改它以从文件而不是字符串中读取应该相当容易。