[我正在尝试通过Java 8中的编译时注释处理为源代码生成配置文件。
据我了解,对于getSupportedAnnotationTypes
类中列出的每个注释,处理器都会被调用一次。
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> set = new LinkedHashSet<>();
set.add(MCPlugin.class.getCanonicalName());
set.add(MCAPIVersion.class.getCanonicalName());
set.add(MCAuthor.class.getCanonicalName());
set.add(MCAPIVersion.class.getCanonicalName());
set.add(MCDepend.class.getCanonicalName());
set.add(MCLoad.class.getCanonicalName());
set.add(MCLoadBefore.class.getCanonicalName());
set.add(MCSoftDepend.class.getCanonicalName());
set.add(MCCommand.class.getCanonicalName());
return set;
}
实际上,我不想使用一个注释处理程序来处理所有这些注释(这是正确的方法吗?),因为它会导致MCCommand
注释出现问题。因此,我的计划是创建另一个注释处理程序,该处理程序仅处理MCCommand
注释。
我的问题是,两个处理器的输出都应放入相同的输出文件中。 (有可能吗?)
我已经尝试过像这样重新打开资源文件(这也是我首先打开它的方式:]
FileObject file = filer.createResource(StandardLocation.SOURCE_OUTPUT, "", "config.yml");
只会创建一个错误或覆盖现有文件。
TlDr:如何使我的注释处理器编辑另一个注释处理器生成的文件?
JavacFiler
,您需要将com.sun.tools作为依赖项。将Filer
下放到JavacFiler
以访问更多方法。文件管理器具有createResource(...)
和getResource(...)
方法,它们看起来似乎相同,但不同之处在于createResource(...)
打开仅用于写入的FileObject
和仅用于读取的getResource(...)
。
因此,要能够从另一个注释处理器编辑文件,请执行以下操作:
以只读方式打开文件
FileObject jfo = filer.getResource(StandardLocation.SOURCE_OUTPUT, "", "test.txt");
String msg = TUtils.JFOToString(jfo); // Reads FileObject as String
jfo.delete();
jfo = filer.createResource(StandardLocation.SOURCE_OUTPUT, "", "test.txt");
TUtils.writeJFO(jfo, msg + "Hallo ich bin Processor 2"); // Writes String to FileObject
filer.close();