java - 使用注释处理器向类型添加属性

标签 java annotations

我正在尝试编写一个应该在编译期间运行的注释处理器。 它将首先检查给定类中是否存在特定字段(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/

相关文章:

swift - 使用detailCalloutAccessoryView作为第三个注释属性

java - 使用 XML 而不是通过注释配置 hibernate 有充分的理由吗?

java - Hibernate - 如何通过注释设置 sql-type?

java - Android onActivityResult() 在图像捕获时返回 NullPointerException

java - 从 java 代码调用 Snarl

java - Log4j 2 根记录器覆盖一切?

java - 当我在 Android 应用程序中创建图像时拍照时,会在 DCIM/Camera 中生成副本

java - 安装 Talend Data Integration Studio 时 Java JRE 和 Eclipse 出现问题

java - 安卓工作室 : @Override "Annotations are not allowed here"

java - 许多方法的 Swagger ApiImplicitParams 注释