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

时间:2025-03-11 07:20:00
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.