发布时间:2023-09-21 18:30
public class ExcelImportValid {
/**
* Excel导入字段校验
*
* @param object 校验的JavaBean 其属性须有自定义注解
*/
public static void valid(Object object) throws BindException {
Field[] fields = object.getClass().getDeclaredFields();
//相当于拆分遍历每个字段
for (Field field : fields) {
//设置可访问
field.setAccessible(true);
//属性的值
Object fieldValue = null;
try {
fieldValue = field.get(object);
} catch (IllegalAccessException e) {
throw new BindException(field.getAnnotation(ExcelValid.class).message());
}
//是否包含必填校验注解
boolean isExcelValid = field.isAnnotationPresent(ExcelValid.class);
if (isExcelValid && ObjectUtils.isEmpty(fieldValue)) {
throw xxx.COMMON_ERROR.e18(field.getAnnotation(ExcelValid.class).message());
}
if(ObjectUtils.isNotEmpty(fieldValue)){
//是否包含日期校验注解
boolean isExcelDate = field.isAnnotationPresent(ExcelDate.class);
if (isExcelDate && !ValidatorUtil.isDate(fieldValue.toString())) {
log.info("当前解析异常日期字段:" + fieldValue.toString());
throw xxx.COMMON_ERROR.e18(field.getAnnotation(ExcelDate.class).message());
}
//是否包含年月校验注解
boolean isExcelMonth = field.isAnnotationPresent(ExcelMonth.class);
if (isExcelMonth && !ValidatorUtil.isMonth(fieldValue.toString())) {
log.info("当前解析异常年月字段:" + fieldValue.toString());
throw xxx.COMMON_ERROR.e18(field.getAnnotation(ExcelMonth.class).message());
}
//是否包含数字校验注解
boolean isExcelNumber = field.isAnnotationPresent(ExcelNumber.class);
if (isExcelNumber && !ValidatorUtil.isPositiveNumber(fieldValue.toString())) {
log.info("当前解析异常数字字段:" + fieldValue.toString());
throw xxx.COMMON_ERROR.e18(field.getAnnotation(ExcelNumber.class).message());
}
//枚举校验注解
boolean isExcelEnum = field.isAnnotationPresent(ExcelEnum.class);
if (isExcelEnum) {
ExcelEnum excelEnum = field.getAnnotation(ExcelEnum.class);
Enum>[] enumConstants = excelEnum.enumClass().getEnumConstants();
//校验是否为枚举类中的值
Boolean flag = false;
for (Enum> enumConstant : enumConstants) {
try {
Method method = enumConstant.getClass().getMethod("getDisplayName");
// 如果有值相等则返回true
Object status = method.invoke(enumConstant);
if (status.equals(fieldValue)){
flag = true;
}
} catch (Exception e) {
log.info("枚举校验异常:", e);
}
}
if(!flag){
log.info("当前解析异常枚举字段:" + fieldValue.toString());
throw xxx.COMMON_ERROR.e18(field.getAnnotation(ExcelEnum.class).message());
}
}
}
}
}
}