java8 之后才允许重复注解, 即在方法上声明多个相同的注解.
具体的代码需要在创建自定义注解时, 声明 @java.lang.annotation.Repeatable
里面的参数是新建的另外一个注解类, 这个注解包含 value() 方法, 返回值是我们目标注解数组
@Repeatable(MyAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
int value();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotations {
MyAnnotation[] value();
}
// jdk8 之前也是可以手动实现重复注解的 @MyAnnotations({@MyAnnotation(1), MyAnnotation(2)})
// jdk8 后, 标注 @Repeatable 的注解, 允许使用重复注解
@MyAnnotation(1)
@MyAnnotation(2)
public void foo() throws Exception {
Class<? extends AnnotationTest> clazz = getClass();
Method method = clazz.getMethod("foo");
// 获取方法上该注解的数组
Annotation[] annotations = method.getAnnotationsByType(MyAnnotation.class);
Object result = method.invoke(this);
}