JDK1.8新特性--重复注解

一、重复注解

在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();
}

结果如图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值