英雄非无泪,不洒敌人前。男儿七尺躯,愿为祖国捐。——陈辉
在java
中如果我们需要一个注解能被重复使用
例如这个
package com.ruben.annotation;
import java.lang.annotation.*;
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface BeanFieldSort {
int order();
}
|
如果我们直接重复注解,会发现编译错误
![image-20210211134907218](https://waibi.oss-cn-chengdu.aliyuncs.com/picGo/image-20210211134907218.png)
我们需要在注解上加上@Repeatable
注解,里面参数放另外一个注解,作为它的承载
package com.ruben.annotation;
import java.lang.annotation.*;
@Repeatable(BeanFieldSort.BeanFieldSorts.class) @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface BeanFieldSort {
int order();
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface BeanFieldSorts { BeanFieldSort[] value(); } }
|
这样就可以重复注解了
![image-20210211135034374](https://waibi.oss-cn-chengdu.aliyuncs.com/picGo/image-20210211135034374.png)
如果我们需要取出注解里面的order
使用之前的方式就会报空指针了,运行结果也打印出来为true
Field field = UserInfo.class.getDeclaredField("serialVersionUID"); BeanFieldSort empty = field.getAnnotation(BeanFieldSort.class); System.out.println("---"); System.out.println(Objects.isNull(empty));
|
![image-20210211135659010](https://waibi.oss-cn-chengdu.aliyuncs.com/picGo/image-20210211135659010.png)
正确方式是使用
Field field = UserInfo.class.getDeclaredField("serialVersionUID"); BeanFieldSort.BeanFieldSorts annotation = field.getAnnotation(BeanFieldSort.BeanFieldSorts.class); for (BeanFieldSort beanFieldSort : annotation.value()) { System.out.println(beanFieldSort.order()); }
|
即可
![image-20210211135736456](https://waibi.oss-cn-chengdu.aliyuncs.com/picGo/image-20210211135736456.png)