当前位置: 代码迷 >> java >> 如何在注释处理器中获取注释参数
  详细解决方案

如何在注释处理器中获取注释参数

热度:90   发布时间:2023-07-25 19:18:11.0

我正在编写自己的注释处理器,并且我正在尝试获取注释的参数,例如在 process 方法中的以下代码中:

roundEnv.getElementsAnnotatedWith(annotation).forEach {
        val annotation = it.getAnnotation(annotation)
        annotation.interfaces
}

我得到的是An exception occurred: javax.lang.model.type.MirroredTypesException: Attempt to access Class objects for TypeMirrors [] during build. 有人知道如何获取注释数据吗?

getAnnotation方法的文档解释了为什么Class<?>对象对于注释处理器有问题:

此方法返回的注释可能包含一个元素,其值为 Class 类型。 该值无法直接返回:定位和加载类所需的信息(例如要使用的类加载器)不可用,并且该类可能根本无法加载。 尝试通过调用返回的注解上的相关方法来读取 Class 对象将导致 MirroredTypeException,从中可以提取相应的 TypeMirror。 同样,尝试读取 Class[] 值的元素将导致 MirroredTypesException。

要访问类等注释元素,您需要使用Element.getAnnotationMirrors()并手动查找感兴趣的注释。 这些注释镜像将包含表示实际值的元素,但不需要存在相关类。

这篇似乎是如何做到这一点的规范来源。 它引用了 Sun 论坛的讨论,并在许多注释处理器中被引用。

对于以下注释:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Action {
    Class<?> value();
}

Class<?>类型的字段可以通过以下代码访问:

for (ExecutableElement ee : ElementFilter.methodsIn(te.getEnclosedElements())) {
    Action action = ee.getAnnotation(Action.class);
    if (action == null) {
        // Look for the overridden method
        ExecutableElement oe = getExecutableElement(te, ee.getSimpleName());
        if (oe != null) {
            action = oe.getAnnotation(Action.class);
        }
    }

    TypeMirror value = null;
    if (action != null) {
        try {
            action.value();
        } catch (MirroredTypeException mte) {
            value = mte.getTypeMirror();
        }
    }

    System.out.printf(“ % s Action value = %s\n”,ee.getSimpleName(), value);
}
  相关解决方案