从可重复的注释属性中获取类

时间:2017-12-15 05:08:45

标签: java annotations

我有一个可重复的注释,其中包含Class类型属性。

@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.PARAMETER)
public @interface MyAnnotation {
    Class<?> value();
}

我尝试使用AnnotationMirror来获取其中的类名,因为我无法获得MirroredTypeException直接获取该类。这与this question相同,只是这个注释是可重复的,这意味着它包含在另一个注释中,就像这个注释一样。

@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.PARAMETER)
public @interface MyAnnotationWrapper {
    MyAnnotation[] value();
}

我只能弄清楚如何为包装器注释获取镜像而不是可重复的镜像。我能够使用链接问题中的hacky变通方法结合通过反射调用注释方法并从我获得的异常中获取原因来完成我需要的工作。它看起来像这样(我现在没有代码在我面前)。

try {
  annotation.getClass().getMethod("value").invoke(annotation)
} catch (<Several exception types> e) {
  className = ((MirroredTypeException) e.getCause()).getTypeMirror().toString()
}

我想知道在这种情况下是否有正确的方法来获取类名。

1 个答案:

答案 0 :(得分:0)

抓住并使用getTypeMirror确实是正确的方法。

您可以使用我的实用程序方法通过方法调用来获取TypeMirror,而不是用字符串反映。

  /**
   * For Class attribute, if we invoke directly, it may throw {@link MirroredTypeException} because the class has not be
   * compiled. Use this method to get the Class value safely.
   *
   * @param elements Elements for convert Class to TypeMirror
   * @param anno annotation object
   * @param func the invocation of get Class value
   * @return the value's {@link TypeMirror}
   */
  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();
    }
  }

用法

  getAnnotationClassValue(elements, annotation, MyAnnotation::value)

为了重复包装,您应该获取数组值并逐个获得TypeMirror