アノテーションクラス
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface A {
}親クラス
@A
public class ParentClass {
    public ParentClass() {}
    @A
    public void hoge() {
        System.out.println("parent hoge");
    }
}子クラス
public class ChildClass extends ParentClass {
    public ChildClass() {}
   
    public void hoge() {
        System.out.println("child hoge");
    }
}実行クラス
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class AnnotationTest {
    public AnnotationTest() {}
    public static void main(String args[]) throws Exception {
        Class clazz = ChildClass.class;
        //クラスのアノテーション取得
        Annotation[] anns = clazz.getAnnotations();
        for (Annotation a : anns) {
            System.out.println("class:  " + a.annotationType());
        }
        // メソッドのアノテーション取得
        Method m = clazz.getMethod("hoge");
        anns = m.getAnnotations();
        for (Annotation a : anns) {
            System.out.println("method:  " + a.annotationType());
        }
    }
}実行結果
class: interface A
クラスのアノテーションは取得可能でオーバライドしたメソッドは取得不可でした。
まぁオーバライドしたら子クラスのメソッドでクラスが構築されるのだから当然といえば当然ですな。
オーバライドしなければもちろんメソッドも取得可能です。
ちなみにアノテーションクラスに@Inheritedをつけないとクラスのアノテーション取得不可ですね。
0 件のコメント:
コメントを投稿