组合注解(Annotation)

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author: lihui
 * @date: 2020-05-20
 */
public class CompositeAnnotationStudy {
    public static void main(String[] args) {
        AnnotationTwo annotationTwo = ClassInAnnotation.class.getAnnotation(AnnotationTwo.class);
        System.out.println(annotationTwo.basePackages());
        AnnotationOne annotationOne = annotationTwo.annotationType().getAnnotation(AnnotationOne.class);
        System.out.println(annotationOne.value());

        System.out.println(annotationTwo.getClass().getAnnotation(AnnotationOne.class));
    }
}

@AnnotationTwo()
class ClassInAnnotation {
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AnnotationOne 
@interface AnnotationTwo {
    String basePackages() default "basePackages";
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented 
@interface AnnotationOne {
    String value() default "value";
}

输出如下:

basePackages
value
null
可以看到:一个注解就可以得到许多种注解的信息。 
注意:
获得一个注解的注解不是通过这种方式:
annotation.getClass().getAnnotation(AnnotationOne.class);
而是通过以下方式:
annotation.annotationType().getAnnotation(AnnotationOne.class);
posted @ 2020-05-20 19:18  eaglelihh  阅读(1640)  评论(0编辑  收藏  举报