利用反射做类参数的校验

需求描述

业务需求描述:对webservice接口参数校验

代码实现

  /**
     * 字符串长度校验
     * 
     * @param str
     * @param len
     * @return 合法(true),不合法(false)
     */
    public static boolean check(String str, int len) {
        if (null != str && str.length() > len) {
            return false;
        }
        return true;
    }

    /**
     * 参数校验
     * 
     * @param data
     * @return 合法(true),不合法(false)
     * @throws IntrospectionException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static List<String> checkParamLength(Object obj)
            throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        List<String> list = new ArrayList<String>();
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            String key = field.getName();
            PropertyDescriptor descriptor = new PropertyDescriptor(key, clazz);
            Method method = descriptor.getReadMethod();
            String value = (String) method.invoke(obj);
            if (!check(value, Constants.ParamMap.get(key))) {
                list.add("error param: " + key + "=> actualLen: " + value.length() + " maxLen: "
                        + Constants.ParamMap.get(key));
            }
        }
        return list;
    }

后续会使用反射机制中的【注解】实现这个功能。

原文地址:https://www.cnblogs.com/Joy-Hu/p/7678355.html