Annotation之補充

  Annotation之補充

@Inherited

表示一個Annotation能否被使用其類的子類繼續繼承下去,如果沒有寫上此註釋,則此Annotation根本就是無法繼承的。

官方解釋:指示註釋類型被自動繼承。如果在註釋類型聲明中存在 Inherited 元註釋,並且用戶在某一類聲明中查詢該註釋類型,同時該類聲明中沒有此類型的註釋,則將在該類的超類中自動查詢該註釋類型。此過程會重複進行,直到找到此類型的註釋或到達了該類層次結構的頂層 (Object) 爲止。如果沒有超類具有該類型的註釋,則查詢將指示當前類沒有這樣的註釋。

具體實例

MyAnnotation

  1. import java.lang.annotation.Documented; 
  2. import java.lang.annotation.ElementType; 
  3. import java.lang.annotation.Inherited; 
  4. import java.lang.annotation.Retention; 
  5. import java.lang.annotation.RetentionPolicy; 
  6. import java.lang.annotation.Target; 
  7. @Inherited //添加此句
  8. @Target(ElementType.METHOD) 
  9. @Retention(RetentionPolicy.RUNTIME) 
  10. @Documented 
  11. public @interface MyAnnotation { 
  12. public String name() default "singsong"

 

Person類中使用Annotation

  1. public class Person { 
  2.     @MyAnnotation(name = "The person's name is singsong"
  3.     public void getName() { 
  4.     }     

 Students類繼承Person

  1. public class Students extends Person { 
  2.  

使用反射機制來實現Students類繼承的註釋

  1. import java.lang.reflect.Method; 
  2. public class TestMyAnnotation { 
  3.     public static void main(String[] args) throws Exception { 
  4.         Class<?> c=Students.class
  5.         Method method=c.getMethod("getName"); 
  6.         MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class); 
  7.         System.out.println(myAnnotation.name()); 
  8.     } 

運行結果:

The person's name is singsong

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章