先上注解:
@AtLeastOneNotEmpty
使用:
@AtLeastOneNotEmpty(fields = {"name1","name2"},message = "name1,name2必填其一")
@AtLeastOneNotEmpty(fields = {"name3","name4"},message = "name3,name4必填其一")
上源码:
AtLeastOneNotEmpty 注解类
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(
validatedBy = {AtLeastOneNotEmptyValidator.class}
)
@Repeatable(AtLeastOneNotEmpties.class)
@Documented
public @interface AtLeastOneNotEmpty {
String message() default "至少有一个属性不可为空";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String[] fields();
}
支持多个校验:
AtLeastOneNotEmpties
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AtLeastOneNotEmpties {
AtLeastOneNotEmpty[] value();
}
逻辑实现代码:
public class AtLeastOneNotEmptyValidator extends AbstractValidator<AtLeastOneNotEmpty, Object> {
private String[] fields;
public AtLeastOneNotEmptyValidator() {
}
public void initialize(AtLeastOneNotEmpty atLeastOneNotEmpty) {
this.fields = atLeastOneNotEmpty.fields();
}
public boolean check(Object object, WrapperHibernateConstraintValidatorContext wrapperHibernateConstraintValidatorContext) {
if (object == null) {
return true;
} else {
try {
String[] var3 = this.fields;
int var4 = var3.length;
for(int var5 = 0; var5 < var4; ++var5) {
String fieldName = var3[var5];
Object value = this.getFieldValue(object, fieldName);
if (this.notEmpty(value)) {
return true;
}
}
return false;
} catch (Exception var8) {
throw new IllegalStateException(var8);
}
}
}
private Object getFieldValue(Object object, String fieldName) throws IllegalAccessException {
if (object == null) {
return null;
} else {
Class<?> clazz = object.getClass();
Field[] classFields = clazz.getDeclaredFields();
Field[] var5 = classFields;
int var6 = classFields.length;
for(int var7 = 0; var7 < var6; ++var7) {
Field field = var5[var7];
if (field.getName().equals(fieldName)) {
field.setAccessible(true);
return field.get(object);
}
}
return null;
}
}
private boolean notEmpty(Object value) {
if (Objects.isNull(value)) {
return false;
} else {
return value instanceof String ? StringUtils.isNotBlank((String)value) : true;
}
}
}