应用场景
某个字段的值校验依赖于另一个字段的值
举例:当字段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, Class().getDeclaredFields());Collections.addAll(fieldList, Class().getSuperclass().getDeclaredFields());for (Field field : fieldList) {NotNullWhen annotation = DeclaredAnnotation(NotNullWhen.class);if (annotation == null) {continue;}Field dependsOnField = null;try {dependsOnField = Class().getDeclaredField(annotation.dependsOnField());} catch (NoSuchFieldException e) {e.printStackTrace();throw ServiceException.of(ResultCode.PARAM_INVALID);}try {dependsOnField.setAccessible(true);Object value = (validateObject);if (value == null) {continue;}if (Arrays.stream(annotation.dependsOnFieldValues()).anyMatch(v -> String.valueOf(value).equals(v))) {Object annotationFieldValue = null;field.setAccessible(true);annotationFieldValue = (validateObject);if (Type() == Integer.class || Type() == Long.class) {if (annotationFieldValue == null || (Long.parseLong(String.valueOf(annotationFieldValue)) < annotation.min())) {throw ServiceException.ofWarn(ResultCode.PARAM_INVALID, ssage());}}if (field.
本文发布于:2024-02-03 04:35:35,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170690613548685.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |