zoukankan      html  css  js  c++  java
  • 利用反射做类参数的校验

    需求描述

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

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

  • 相关阅读:
    InnoDB in Mysql
    Store engine for Mysql
    Replication in Mysql
    Mysql note 3
    查看SQL对象的创建脚本
    Mysql note 2
    Jsp登录后数据采集奇怪的Apache服务器
    一行代码收集页
    使用Subsonic与ObjectDataSource(ODS)
    二分查找
  • 原文地址:https://www.cnblogs.com/Joy-Hu/p/7678355.html
Copyright © 2011-2022 走看看