1: Define annotation A
@Retention(RetentionPolicy.RUNTIME)
public @interface A {
}
2: Define annotation B and use annotation A annotation
@A
@Retention(RetentionPolicy.RUNTIME)
public @interface B {
}
3: Define the class and use the annotation B annotation
@B
public class Cls {
}
4: Get all the annotations of the Cls class
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);
}
}
Perform the test:
annotationB:
@compositeannotation.B()
annotationA:
@compositeannotation.A()