分享几个实用的参数校验注解(含字段依赖校验、枚举字段值有效性校验、参数类型转换)

阅读: 评论:0

分享几个实用的参数校验注解(含字段依赖校验、枚举字段值有效性校验、参数类型转换)

分享几个实用的参数校验注解(含字段依赖校验、枚举字段值有效性校验、参数类型转换)

字段依赖校验相关代码

应用场景

某个字段的值校验依赖于另一个字段的值
举例:当字段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 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23