java8的注解-Repeatable

Java8注解新增两个主要特性,一个类型注解,目前没看到什么用,留着再研究吧(坏习惯!),另一个就是我要说的这个新特性Repeatable感觉棒棒的,可以一次传好多值啦。来看我的这个 Demo

###code

public class RepeatableAnnotationDemo {
    public static void main(String[] args) {
        testRepeatable();
    }

    @myAnno(str = "hs", size = 2)
    @myAnno(str = "Ys", size = 1)
    @myAnno(str = "zs", size = 3)
    public static void testRepeatable() {
        try {
            Class<?> clazz = Class.forName("Book.RepeatableAnnotationDemo");
            Method method = clazz.getMethod("testRepeatable");
            RepeatableAnno annotation = method.getAnnotation(RepeatableAnno.class);
            System.out.println(annotation);
            myAnno[] annos1 = annotation.value();
            for (myAnno anno : annos1) {
                System.out.println(anno + "->size:" + anno.size() + " str:" + anno.str());
            }
            System.out.println("------------------------------------------------");
            myAnno[] annos = method.getAnnotationsByType(myAnno.class);
            for (myAnno anno : annos) {
                System.out.println(anno + "->size:" + anno.size() + " str:" + anno.str());
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

@Retention(RetentionPolicy.RUNTIME)
@Repeatable(RepeatableAnno.class)
@interface myAnno {
    String str() default " ";

    int size() default 0;
}

@Retention(RetentionPolicy.RUNTIME)
@interface RepeatableAnno {
    myAnno[] value();
}

@Book.RepeatableAnno(value=[@Book.myAnno(size=2, str=hs), @Book.myAnno(size=1, str=Ys), @Book.myAnno(size=3, str=zs)])
@Book.myAnno(size=2, str=hs)->size:2 str:hs
@Book.myAnno(size=1, str=Ys)->size:1 str:Ys
@Book.myAnno(size=3, str=zs)->size:3 str:zs
------------------------------------------------
@Book.myAnno(size=2, str=hs)->size:2 str:hs
@Book.myAnno(size=1, str=Ys)->size:1 str:Ys
@Book.myAnno(size=3, str=zs)->size:3 str:zs

转载于:https://my.oschina.net/xd03122049/blog/862038

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值