一、重复注解
在JDK1.8之后标注在类,方法等上面的注解可以重复出现,如下图
但是如果你直接在方法等上面注多个相同的注解,程序还是会报错,错误信息提示注解MyAnnotation没有被一个Repeatable注解修饰,而Repeatable注解里面传入的参数必须也是一个注解,这个注解所包含的值必须有一个要重复注解的这个注解类型的数组。我们同样可以和以前一样通过反射得到注解的值,如下代码
public class TestAnnotation {
@MyAnnotation("Hello")
@MyAnnotation("World")
public void show(){
}
@Test
public void test01() throws NoSuchMethodException {
Class<TestAnnotation> testAnnotationClass = TestAnnotation.class;
Method show = testAnnotationClass.getMethod("show");
MyAnnotation[] annotationsByType = show.getAnnotationsByType(MyAnnotation.class);
Arrays.stream(annotationsByType)
.map(MyAnnotation::value)
.forEach(System.out::println);
}
}
@Repeatable(MyAnnotations.class)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
String value() default "annotation";
}
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotations{
MyAnnotation[] value();
}
结果如图: