码迷,mamicode.com
首页 > 其他好文 > 详细

利用反射做类参数的校验

时间:2017-10-16 21:39:24      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:ror   red   add   exce   boolean   constant   argument   cep   list   

需求描述

业务需求描述:对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;
    }

 

利用反射做类参数的校验

标签:ror   red   add   exce   boolean   constant   argument   cep   list   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!