2014-05-12 51 views
0

我有註解的列表,並要檢查,如果我的自定義註釋「MyAnnotation」包含在此列表:檢查註釋包含在註釋列表

List<java.lang.annotation.Annotation> 

我的註解:

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
public @interface MyAnnotation { 

} 

什麼是檢查的最佳方法。我是否需要在列表中進行交流並比較名稱,或者是否有某種方法可以獲取「contains()」 - 要在此處工作的列表的方法?

回答

2

如果我正確地得到您的問題,那麼根據Annotation.equals(java.lang.Object)的文檔,您應該可以在列表中使用方法。

如果指定的對象表示與此邏輯等效的註釋,則返回true。

  • 兩個對應原始類型化:換句話說,如果指定的對象是相同的註釋類型與該實例的一個實例,則返回true,其所有成員都等於該註釋的相應部件,如下面所定義如果x == y,則其值爲x和y的成員被認爲是相等的,除非它們的類型是float或double。
  • 如果Float.valueOf(x).equals(Float.valueOf(y))被認爲是相等的,則其值爲x和y的兩個相應的float成員相等。 (與==運算符不同,NaN被認爲與自己相等,而0.0f不等於-0.0f)
  • 如果Double.valueOf(x).equals( Double.valueOf(Y))。 (與==運算符不同,NaN被認爲與自己相等,0.0不等於-0.0)
  • 如果x.equals被認爲是相等的,那麼其值爲x和y的兩個相應的String,Class,enum或annotation類型成員(Y)。 (請注意,此定義對於註釋類型成員是遞歸的。)
  • 如果Arrays.equals(x,y)適當重載Arrays.equals(long []),則認爲兩個對應的數組類型成員x和y相等,長[])。

而且下面的演示片斷,它的輸出似乎證明這一點 -

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
@interface MyAnnotation { 
    String value(); 
} 

public class Main { 
    @MyAnnotation(value = "onM1") public static void m1() { } 
    @MyAnnotation(value = "onM1") public static void m() { } 
    @MyAnnotation(value = "onM2") public static void m2() { } 
    @MyAnnotation(value = "onM3") public static void m3() { } 


    public static void main(String[] args) throws Exception { 
     Method m = Main.class.getMethod("m1", new Class<?>[] {}); 
     Annotation onM1 = m.getAnnotation(MyAnnotation.class); 

     m = Main.class.getMethod("m2", new Class<?>[] {}); 
     Annotation onM2 = m.getAnnotation(MyAnnotation.class); 

     m = Main.class.getMethod("m3", new Class<?>[] {}); 
     Annotation onM3 = m.getAnnotation(MyAnnotation.class); 

     m = Main.class.getMethod("m", new Class<?>[] {}); 
     Annotation onM = m.getAnnotation(MyAnnotation.class); 

     List<Annotation> annots = Arrays.asList(onM1, onM2); 

     System.out.println(annots); 
     System.out.println(annots.contains(onM3)); 
     System.out.println(annots.contains(onM1)); 
     System.out.println(annots.contains(onM2)); 
     System.out.println(annots.contains(onM)); 
    } 
} 

輸出

 
false 
true 
true 
true 
+0

感謝這就是正確的,並幫助例子我很多瞭解我的問題 – jan

+0

不客氣。 –

0
boolean containsMyAnnotation = false; 
// For each annotation in the list... 
for(Annotation annotation : myListOfAnnotations) { 
    // If they are MyAnnotation 
    if(annotation.class == MyAnnotation.class) { 
     // Then it exists in the list 
     containsMyAnnotation = true; 
     // Break the for loop 
     break; 
    } 
}