标签:ali style equal ota 对象 excel message throw stat
getFields():获得某个类的所有的公共(public)的字段,包括父类中的字段。
getDeclaredFields():获得某个类的所有声明的字段,即包括public、private和proteced,但是不包括父类的申明字段。
/** * 获取本类及其父类的属性 * @param clazz 当前类对象 * @return 字段数组 */ private static List<Field> getAllFields(Class<?> clazz) { List<Field> fieldList = new ArrayList<>(); while (clazz != null){ fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()))); clazz = clazz.getSuperclass(); } return fieldList; }
public class EasyExcelValidHelper { private EasyExcelValidHelper(){} private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); public static <T> String validateEntity(T obj) throws Exception { StringBuilder result = new StringBuilder(); Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class); if (set != null && !set.isEmpty()) { for (ConstraintViolation<T> cv : set) { Optional<Field> fieldOptional = getAllFields(obj.getClass()) .stream().filter(i -> cv.getPropertyPath().toString().equals(i.getName())).findAny(); if (fieldOptional.isPresent()) { Field declaredField = fieldOptional.get(); ExcelProperty annotation = declaredField.getAnnotation(ExcelProperty.class); //拼接错误信息,包含当前出错数据的标题名字+错误信息 result.append(annotation.value()[0]).append(cv.getMessage()).append(";"); }else{ throw new RuntimeException("系统异常"); } } } return result.toString(); } /** * 获取本类及其父类的属性 * @param clazz 当前类对象 * @return 字段数组 */ private static List<Field> getAllFields(Class<?> clazz) { List<Field> fieldList = new ArrayList<>(); while (clazz != null){ fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()))); clazz = clazz.getSuperclass(); } return fieldList; } }
标签:ali style equal ota 对象 excel message throw stat
原文地址:https://www.cnblogs.com/yuming2018/p/14148130.html