Tag: 代码生成

使用注释处理器替换代码

我正在尝试编写一个注释处理器来在类上插入方法和字段……而且文档非常稀疏。 我没有走远,我不知道我是否正确接近它。 处理环境提供了一个Filer对象,该对象具有创建新的源文件和类文件的便捷方法。 那些工作正常,但后来我试图弄清楚如何读取现有的源文件,它提供的只是“getResource”。 所以在我的处理器实现中,我做到了这一点: @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { try { for (TypeElement te : annotations) { for (Element element : roundEnv.getElementsAnnotatedWith(te)) { FileObject in_file = processingEnv.getFiler().getResource( StandardLocation.SOURCE_PATH, “”, element.asType().toString().replace(“.”, “/”) + “.java”); FileObject out_file = processingEnv.getFiler().getResource( StandardLocation.SOURCE_OUTPUT, “”, element.asType().toString().replace(“.”, “/”) + “.java”); //if (out_file.getLastModified() >= in_file.getLastModified()) continue; CharSequence data = […]

是否有可能以编程方式仅在内存中编译java源代码?

我找到了很多参考资料,解释了如何使用JavaCompiler类以编程方式编译Java类: JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); int result = compiler.run(null, null, null, “a_file_name”); 但是,我想知道是否有一个开源库让我编译以编程方式生成的源代码(因此不涉及src文件)并在输出流中生成一些字节代码(不在文件系统中生成类文件) )。 例如,我正在寻找能够写这样的东西: InputStream input = generateSourceCode(); OutputStream output = getByteCode(input); doCoolStuffWithByteCode(output); 谢谢你的帮助。