2016-12-01 30 views
0

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,而不是MethodField對象。

+2

爲什麼在閱讀Oracle文檔時遇到[SO文檔](http://stackoverflow.com/documentation/java/157/annotations/9902/repeating-annotations#t=201612010146085258575)? ;) – shmosel

+0

@shmosel感謝您的鏈接,這是SO文檔比規範文檔更有用的一個很好的例子。 – dimo414

回答

0

文檔的「檢索註釋」部分在描述檢索重複註釋的正確方法方面做得並不出色。他們提到.getAnnotationByType()作爲遺產代碼有用,並且getAnnotations(Class<T>)方法doesn't exist

缺少方法最初迷惑我,所以我堅持的傳統行爲(因此輔助方法),但正確的方法似乎是.getAnnotationsByType()負責處理這兩種情況下(和作爲獎金永遠不會返回null),這樣你就可以簡單地說:

yourMethod.getAnnotationsByType(YourRepeatableAnnotation.class) 

獲得上所有@YourRepeatableAnnotation註釋,或者如果該方法沒有被標註一個空數組。