如何在另一个注释中获取带注释的元素?

问题描述 投票:0回答:1

我有两个注释:

@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
public @interface A {
    Parameter[] parameters() default {};
    //other methods
}


@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface Parameter {
    Class<?> parameterClass();
}

使用这样:

@A(parameters = @Parameter(parameterClass = Integer.class))
public class C{}

我可以使用列注释获取元素:

Set<? extends Element> annotatedElements = roundEnvironment.getElementsAnnotatedWith(A.class);
Set<TypeElement> types = ElementFilter.typesIn(annotatedElements);
for (TypeElement e : types) {
    A a = e.getAnnotation(A.class);
    //do something...
    //I can get Parameters:
    Parameter[] parameters = a.parameters();
    ...
}

但我不能直接从参数中获取parameterClass。所以我需要获取Element / AnnotationMirror。我能这样做吗?怎么样?

java reflection annotations
1个回答
0
投票

类对象可能无法在当前编译期间编译,因此它可能会抛出MirroredTypeException。你可以从例外中获得TypeMirro

这是我的实用方法:

  public static <T extends Annotation> TypeMirror getAnnotationClassValue(Elements elements, T anno,
      Function<T, Class<?>> func) {
    try {
      return elements.getTypeElement(func.apply(anno).getCanonicalName()).asType();
    } catch (MirroredTypeException e) {
      return e.getTypeMirror();
    }
  }

你可以做

Parameter p = parameters[0];
TypeMirror tm = getAnnotationClassValue(elements, p, Parameter::parameterClass);
© www.soinside.com 2019 - 2024. All rights reserved.