字段依赖校验相关代码
应用场景
某个字段的值校验依赖于另一个字段的值
举例:当字段A in {1,2,3}时,字段B不能为空
注解声明
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({
ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNullWhen {
//当前字段最小值
long min() default 0;
//依赖字段名
String dependsOnField();
//依赖字段值域
String[] dependsOnFieldValues();
//校验失败时的提示信息
String message() default "";
}
注解处理类
public class ParamValidator {
public static void validateWithDepends(Object validateObject) {
List<Field> fieldList = new ArrayList<>();
Collections.addAll(fieldList, validateObject.getClass().getDeclaredFields());
Collections.addAll(fieldList, validateObject.getClass().getSuperclass().getDeclaredFields());
for (Field field : fieldList) {
NotNullWhen annotation = field.getDeclaredAnnotation(NotNullWhen.class);
if (annotation == null) {
continue;
}
Field dependsOnField = null;
try {
dependsOnField = validateObject.getClass().getDeclaredField(annotation.dependsOnField());
} catch (NoSuchFieldException e) {
e.printStackTrace();
throw ServiceException.of(ResultCode.PARAM_INVALID);
}
try {
dependsOnField.setAccessible(true);
Object value = dependsOnField.get(validateObject);
if (value == null) {
continue;
}
if (Arrays.stream(annotation.dependsOnFieldValues()).anyMatch(v -> String.valueOf(value).equals(v))) {
Object annotationFieldValue = null;
field.setAccessible(true);
annotationFieldValue = field.get(validateObject);
if (field.getType() == Integer.class || field.getType() == Long.class) {
if (annotationFieldValue == null || (Long.parseLong(String.valueOf(annotationFieldValue)) < annotation.min())) {
throw ServiceException.ofWarn(ResultCode.PARAM_INVALID, annotation.message());
}
}
if (field.