引入 Java 8 repeating annotations ,但不得不将它们塞进不直接支撑它们的现有结构中。他们通过引入一个 @Repeatable
元注释来做到这一点,但是根据一个对象上是否有一个或多个注释,您会得到不同的行为:
If more than one annotation of the requested type is present, you can obtain them by first getting their container annotation.
这意味着如果只有一个注解存在,您不能使用容器注解,而且看起来确实如此。我写了以下内容来一起处理一个和多个案例,但它似乎过于复杂:
public static <C, T> List<T> getAnnotations(
Method m, Class<C> containerClass, Class<T> annotationClass) {
C container = m.getAnnotation(containerClass);
if (container != null && container.value().length > 0) {
return ImmutableList.copyOf(container.value());
}
// apparently the @Container isn't considered set unless
// there's *repeated* @Annotation elements
T annotation = m.getAnnotation(annotationClass);
if (annotation != null) {
return ImmutableList.of(annotation);
}
return ImmutableList.of();
}
有没有更简洁的方法来解决这个问题?文档还提到使用 AnnotatedElement
但我不知道如何使用它;这些方法似乎只接受 Class
对象,而不是 Method
或 Field
对象。
最佳答案
该文档的“检索注释”部分没有很好地描述检索重复注释的正确方法。他们提到 .getAnnotationByType()
对遗留代码有用,以及 getAnnotations(Class<T>)
方法doesn't exist .
缺少的方法最初让我感到困惑,所以我坚持使用遗留行为(因此使用辅助方法),但正确的方法似乎是 .getAnnotationsByType()
它处理这两种情况(作为奖励永远不会返回 null
),所以你可以简单地说:
yourMethod.getAnnotationsByType(YourRepeatableAnnotation.class)
获取所有@YourRepeatableAnnotation
关于 yourMethod
的注释,如果该方法未注释,则为空数组。
关于java - 获取重复注释值的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40901265/