我正在尝试编写一个应该在编译期间运行的注释处理器。
它将首先检查给定类中是否存在特定字段(int id)(编译后),如果不存在,则应该添加该字段(如果可能,初始值为-1)。
我想我有要编辑的 TypeElement
。
例如,我可以在类文件的一行中插入一个字符串吗?
processingEnd.getFilter().getResource(...)
似乎给了我该文件,但我不确定如何
执行此操作并正确指定参数。我可以获得读写流,但我不完全确定是否可以简单地在类中的某行“插入”我想要的内容。
@Override
public boolean process(Set<? extends TypeElement> set,
RoundEnvironment round) {
if (!set.contains(DBStorable.class)) {
return false;
}
Set<? extends Element> elements =
round.getElementsAnnotatedWith(DBStorable.class);
for (Element element : elements) {
if (element.getKind() == ElementKind.CLASS) {
// edit processed class to include id field.
TypeElement processedType = (TypeElement) element;
boolean found = false;
for (Element subElement : processedType.getEnclosedElements()) {
if (subElement.getKind() == ElementKind.FIELD
&& subElement.getSimpleName().equals("id")) {
found = true;
break;
}
}
if (!found) {
// This is where I don't get on...
JavaFileObject javaFile = processingEnv.getFiler().getResource(
Location, // <- not sure how to get this.
processingEnv.getElementUtils().getPackageOf(processedType),
processedType.getSimpleName()); // <- is this the right value?
// ... tbc
}
}
}
// TODO Auto-generated method stub
return true;
}
最佳答案
您不应该在处理过程中更改任何类。检查 Filer 的文档类:
In general, processors must not knowingly attempt to overwrite existing files that were not generated by some processor.
但是,您可以创建覆盖现有方法或添加新属性的子类:
Note that some of the effect of overwriting a file can be achieved by using a decorator-style pattern. Instead of modifying a class directly, the class is designed so that either its superclass is generated by annotation processing or subclasses of the class are generated by annotation processing. If the subclasses are generated, the parent class may be designed to use factories instead of public constructors so that only subclass instances would be presented to clients of the parent class.
如果这不适合您,请继续寻找其他工具或解决方法。例如,这个问题可能有一些解决方案适合您:Plugging in to Java compilers
关于java - 使用注释处理器向类型添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23398515/