英雄非无泪,不洒敌人前。男儿七尺躯,愿为祖国捐。——陈辉
在java
中如果我们需要一个注解能被重复使用
例如这个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package com.ruben.annotation;
import java.lang.annotation.*;
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface BeanFieldSort {
int order();
}
|
如果我们直接重复注解,会发现编译错误

我们需要在注解上加上@Repeatable
注解,里面参数放另外一个注解,作为它的承载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| 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(); } }
|
这样就可以重复注解了

如果我们需要取出注解里面的order
使用之前的方式就会报空指针了,运行结果也打印出来为true
1 2 3 4 5
| Field field = UserInfo.class.getDeclaredField("serialVersionUID"); BeanFieldSort empty = field.getAnnotation(BeanFieldSort.class); System.out.println("---"); System.out.println(Objects.isNull(empty));
|

正确方式是使用
1 2 3 4 5
| Field field = UserInfo.class.getDeclaredField("serialVersionUID"); BeanFieldSort.BeanFieldSorts annotation = field.getAnnotation(BeanFieldSort.BeanFieldSorts.class); for (BeanFieldSort beanFieldSort : annotation.value()) { System.out.println(beanFieldSort.order()); }
|
即可
