Annotation之補充
@Inherited
表示一個Annotation能否被使用其類的子類繼續繼承下去,如果沒有寫上此註釋,則此Annotation根本就是無法繼承的。
官方解釋:指示註釋類型被自動繼承。如果在註釋類型聲明中存在 Inherited 元註釋,並且用戶在某一類聲明中查詢該註釋類型,同時該類聲明中沒有此類型的註釋,則將在該類的超類中自動查詢該註釋類型。此過程會重複進行,直到找到此類型的註釋或到達了該類層次結構的頂層 (Object) 爲止。如果沒有超類具有該類型的註釋,則查詢將指示當前類沒有這樣的註釋。
具體實例
MyAnnotation
- import java.lang.annotation.Documented;
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Inherited;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- @Inherited //添加此句
- @Target(ElementType.METHOD)
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- public @interface MyAnnotation {
- public String name() default "singsong";
- }
在Person類中使用Annotation
- public class Person {
- @MyAnnotation(name = "The person's name is singsong")
- public void getName() {
- }
- }
Students類繼承Person類
- public class Students extends Person {
- }
使用反射機制來實現Students類繼承的註釋
- import java.lang.reflect.Method;
- public class TestMyAnnotation {
- public static void main(String[] args) throws Exception {
- Class<?> c=Students.class;
- Method method=c.getMethod("getName");
- MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
- System.out.println(myAnnotation.name());
- }
- }
運行結果:
The person's name is singsong