1:注釈Aを定義する
@Retention(RetentionPolicy.RUNTIME)
public @interface A {
}
2:注釈Bを定義し、注釈A注釈を使用します
@A
@Retention(RetentionPolicy.RUNTIME)
public @interface B {
}
3:クラスを定義し、アノテーションBアノテーションを使用します
@B
public class Cls {
}
4:Clsクラスのすべてのアノテーションを取得します
public class Main {
public static void main(String[] args) {
// 首先直接获取B注解,这是确定的
B annotationB = Cls.class.getAnnotation(B.class);
System.out.println("annotationB: ");
System.out.println(annotationB);
// 通过B的class获取注解A,这里注意使用annotationType()方法,而不是getClass()
// 因为此时返回的是代理对象class,而非本class
A annotationA = annotationB.annotationType().getAnnotation(A.class);
System.out.println("annotationA: ");
System.out.println(annotationA);
}
}
テストを実行します。
annotationB:
@compositeannotation.B()
annotationA:
@compositeannotation.A()