Java 8引入了repeating annotations,但不得不在現有的結構中直接支持它們。他們通過引入@Repeatable
元註釋,但你得到不同的效果,這取決於是否有一個或更比一個註釋對象上:正確的方法來獲得重複註釋的價值?
如果請求的類型的多個註釋存在 ,您可以通過首先獲取它們的容器註釋來獲取它們。
這意味着,如果只有一個註釋存在你不能使用容器註釋,以及LO-和看哪,似乎是這種情況。我寫了下面來處理一個更比1箱子在一起,但似乎過於複雜:
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
對象。
爲什麼在閱讀Oracle文檔時遇到[SO文檔](http://stackoverflow.com/documentation/java/157/annotations/9902/repeating-annotations#t=201612010146085258575)? ;) – shmosel
@shmosel感謝您的鏈接,這是SO文檔比規範文檔更有用的一個很好的例子。 – dimo414