Java根据传入的属性字段名称,校验对象(包含父类对象)中的属性字段值是否存在

2023-05-16

参考文章

在参考文章的基础上,完善了检查父类字段功能。

/**
 * 对象字段检测工具类
 */
public class ValidationUtil {
    
    private static final String PIX_GET = "get";

    /**
     * 根据传入的属性字段名称,校验bean对象(包含父类字段)中的字段值是否存在
     * @param object 对象
     * @param checkedFields 字段英文列表
     * @param checkedFieldsName 字段中文列表
     * @return
     */
    public static Result checkFieldExistEmpty(Object object, List<String> checkedFields, List<String> checkedFieldsName) {
        if (null == object) {
            throw new ServiceException("ValidationUtil#checkFieldExistEmpty object param is null");
        }

        Class<?> aClass = object.getClass();
        // 获取本类所有的字段
        List<Field> fieldList = new ArrayList(Arrays.asList(aClass.getDeclaredFields()));
        // 合并父类的所有字段
        fieldList.addAll(Arrays.asList(aClass.getSuperclass().getDeclaredFields()));
        String fieldName = "";
        StringBuilder methodName = null;
        Method method = null;
        Object result = null;
        for (Field field : fieldList) {
            fieldName = field.getName();
            if (!hasElement(fieldName, checkedFields)) {
                continue;
            }
            methodName = new StringBuilder(PIX_GET);
            // 驼峰式命名,第一个改为大写,后续保持一致。进行getXxx()操作
            methodName = methodName.append(fieldName.substring(0, 1).toUpperCase())
                    .append(fieldName.substring(1));
            try {
                // 获取本类该字段get方法
                method = aClass.getDeclaredMethod(methodName.toString());
            } catch (NoSuchMethodException e) {
                try {
                    // 获取父类该字段get方法
                    method = aClass.getSuperclass().getDeclaredMethod(methodName.toString());
                } catch (NoSuchMethodException ex) {
                    return Result.failed("未找到该字段信息,请检查数据是否正确。");
                }
            } finally {
                try {
                    result = method.invoke(object);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            // 存在空属性
            if (null == result || "".equals(result)) {
                // 获取字段名下标
                int i = checkedFields.indexOf(fieldName);
                // 返回提示消息
                return Result.failed(checkedFieldsName.get(i).concat("不能为空,请完善后重新提交申请。"));
            }
        }

        return Result.succeed("ok");
    }

    /**
     * 检测container数组是否包含element元素
     *
     * @return boolean,true 包含
     */
    private static boolean hasElement(String element, List<String> containers) {
        return containers.contains(element);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java根据传入的属性字段名称,校验对象(包含父类对象)中的属性字段值是否存在 的相关文章

随机推荐