利用反射将请求信息封装为JavaBean升级版(含代码)

1.创建SimpleBeanConvertor封装类

1.1定义convert方法(负责接收并处理请求数据拼接方法和参数)

  /**
     * 将HTTP请求中的参数赋值给指定类型JavaBean的相关属性。
     * @param request HTTP请求
     * @param targetType 目标JavaBean类型
     * @return targetType类型的实例
     */
    public static <T> T convert(HttpServletRequest request, Class<T> targetType)
            throws IllegalAccessException, InstantiationException, ParseException, UnsupportedTypeException, InvocationTargetException {
        Map<String, String[]> params = request.getParameterMap(); // 获取所有请求参数
        if (params.size() == 0) return null;
        T target = targetType.newInstance(); // 创建JavaBean实例
        Method[] allMethods = targetType.getMethods(); // 获取JavaBean中所有方法
        if (allMethods != null && allMethods.length > 0) {
            for (Method method : allMethods) {
                if (method.getName().startsWith("set")) { // 仅处理setter访问器
                    Class[] args = method.getParameterTypes(); // 获取参数列表
                    if (args.length == 1) { // 仅处理单参情况
                        // 获取set方法对应的请求参数:setName → name
                        String paramName = method.getName().substring(3, 4)
                                .toLowerCase() + method.getName().substring(4);
                        if (params.containsKey(paramName)) { // 请求中有此参数
                            try { // 将请求参数值转换为setter方法参数类型
                                Object value = parseValue(params.get(paramName), args[0]);
                                method.invoke(target, value);
                            } catch (ParseException e) {
                                logger.debug("参数转换错误", e);
                                e.printStackTrace();
                                throw e;
                            }
                        } else if (Boolean.class == args[0] || boolean.class == args[0]) {
                            method.invoke(target, false); // 如果是boolean,不存在表示false
                        }
                    }
                }
            }
        }
        return target;
    }

1.2定义parseValue方法(判断参数类型并调用赋值)

    /**
     * 将HTTP请求中String类型的参数值转换为相关属性的类型。
     * 支持String,yyyy-MM-dd格式的日期,基本类型及包装类,BigDecimal,BigInteger
     * 修改此方法可添加对更多类型的支持
     * @param value HTTP请求参数值
     * @param type 属性类型
     * @return 转换后的参数值
     */
    private static Object parseValue(String[] value, Class type) throws ParseException, UnsupportedTypeException {
        if (String.class == type)
            return value[0];
        if (java.util.Date.class == type )
            return new SimpleDateFormat("yyyy-MM-dd").parse(value[0]);
        if (boolean.class == type || Boolean.class == type)
            return true;
        if (char.class == type || Character.class == type)
            return value[0].charAt(0);
        if (int.class == type || Integer.class == type)
            return Integer.valueOf(value[0]);
        if (short.class == type || byte.class == type || long.class == type
                || float.class == type || double.class == type)
            try { // 将值类型变更为对应的包装类型
                type = Class.forName("java.lang." + type.getName().substring(0, 1)
                        .toUpperCase() + type.getName().substring(1));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        if (type.getName().startsWith("java.lang.") || type.getName().startsWith("java.math."))
            try {
                // return type.getMethod("valueOf", String.class).invoke(null, value[0]);
                return type.getConstructor(String.class).newInstance(value[0]);
            } catch (Exception e) {
                throw new UnsupportedTypeException(e);
            }
        throw new UnsupportedTypeException();
    }

2.创建自定义异常类(根据需求)

public class UnsupportedTypeException extends Exception {
    public UnsupportedTypeException() {
        super("不支持的类型转换");
    }
    public UnsupportedTypeException(Throwable e) {
        super("不支持的类型转换", e);
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值