java 8支持同一个属性多次使用相同注解
背景
- 一般情况下同一个注解在一个属性上使用,编译都过不了,如下图所示。

解决方案
- 新建一个注解
import java.lang.annotation.*;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Annotations {
ConditionalValidateField[] value();
}
- 引用刚才的注解
@Repeatable(Annotations.class)
public @interface ConditionalValidateField {
...省略...
}
- 这样子就不报错了

- 这个属性用反射会得到多个注解,也可以直接用
Spring的方法AnnotationUtils.getRepeatableAnnotations(注意5.2版本是过时的)
浙公网安备 33010602011771号