可重复注解

注解可以重复定义多个

@MyAnnotation()

@MyAnnotation(value="123")
class Person{
    private String name;
    private int age;

这就叫重复注解,但这么做报错了
jdk8之前的方式,要用数组来实现重复注解

@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
public @interface MyAnnotation {

    String value() default "hello";
}

public @interface MyAnnotations {
    MyAnnotation[] value();
}

//@MyAnnotation(value="hi")

//@MyAnnotation(value="abc")
@MyAnnotations({@MyAnnotation(value="hi"),@MyAnnotation(value="abc")})
class Person{
    private String name;
    private int age;

    public Person() {

    }

可重复注解的实现步骤:
1.在MyAnnotation上去声明@Repeatable(MyAnnotations.class),成员值为MyAnnotations.class
让这两个注解关联在一起
2.MyAnnotation的Target和Retention和MyAnnotations相同
3.且要么都有@Inherited修饰,要么都没有这个东西修饰,否则运行出错
两者的元注解需要是相同的

@Repeatable(MyAnnotations.class)//MyAnnotation和MyAnnotations的生命周期要一致,否则报错,两者的修饰结构也要相同,所以要用相同的Target
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
public @interface MyAnnotation {

    String value() default "hello";
}

@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
public @interface MyAnnotations {
    MyAnnotation[] value();
}

@MyAnnotation(value="hi")
@MyAnnotation(value="abc")
class Person{
    private String name;
    private int age;

    public Person() {

    }

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值