适用范围:当我们在jsp页面需要接收很多值的时候,如果用request.getParameter(属性名)一个一个写的话那就太麻烦了,于是我想是 否能用反射写个工具类来简化这样的代码,经过1个小时的代码修改调试,终于雏形出来了,很高兴调试成功,呵呵,代码贴出来.

package com.letv.uts2.utcServer.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: haoshihai
 * Date: 13-3-14
 * Time: 下午3:09
 * To change this template use File | Settings | File Templates.
 */
public class WrapperModel {
    private static final Logger log = LoggerFactory.getLogger(WrapperModel.class);
    String userName;
    String password;

public String getUserName() {
        return userName;
    }

public void setUserName(String userName) {
        this.userName = userName;
    }

public String getPassword() {
        return password;
    }

public void setPassword(String password) {
        this.password = password;
    }

public  static <T> T doWrapper(Class c, Map<String, Object> map) throws Exception {
        T t = (T) c.newInstance();
        try {
            Set<Map.Entry<String, Object>> set = map.entrySet();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String fileName = entry.getKey();
                Object value = entry.getValue();
                log.info("fileName={},value={}", new Object[]{fileName, value});
                Method get_Method = c.getMethod("get" + getMethodName(fileName));  //获取getMethod方法
                Method set_Method = c.getMethod("set" + getMethodName(fileName), get_Method.getReturnType());//获得属性get方法
                Class<?> clazz = get_Method.getReturnType();
                String type = clazz.getName(); //获取返回值名称
                if (type.equals("long"))
                    set_Method.invoke(t, Long.valueOf(value.toString()));  //对于类型 long
                else if (type.equals("int") || type.equals("java.lang.Integer"))//对于int 类型
                    set_Method.invoke(t, Integer.valueOf(value.toString()));
                else if ("java.lang.String".equals(type))
                    set_Method.invoke(t,value);
                else set_Method.invoke(t, c.cast(value));//其他类型调用class.cast方法
            }
        } catch (Exception e) {
            log.equals("property is errorr!" + e.toString());
        }
        return t;
    }

// 把一个字符串的第一个字母大写、效率是最高的、

private static String getMethodName(String fildeName) {
        byte[] items = fildeName.getBytes();
        items[0] = (byte) ((char) items[0] - 'a' + 'A');
        return new String(items);
    }

public static void main(String args[]) throws Exception {
        Map map = new HashMap();
        map.put("userName", "jim");
        map.put("password", "tom");
        WrapperModel w2 = (WrapperModel) WrapperModel.doWrapper(WrapperModel.class, map);
        System.out.print(w2.getPassword()+"----"+w2.getUserName());
    }
}

---------------------------------------------------------------------------------------------

package com.student.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

public class BuildBeanUtil {
    @SuppressWarnings("unchecked")
    public <T> T buildBean(HttpServletRequest request,Class<T> beanClass) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        //beanClass set方法
        List<Method> setMethods=new ArrayList<Method>();
        //beanClass set方法名
        List<String> setMethodNames=new ArrayList<String>();
        //beanClass 属性名
        List<String> propertyNames=new ArrayList<String>();
        //表单数据
        List<String> formValues=new ArrayList<String>();
        //1、获得该JavaBean的所有的set方法
        Method[] methods=beanClass.getMethods();
        for(Method m:methods){
            if(m.getName().indexOf("set")==0){
                setMethods.add(m);
            }
        }
        //2、实例化该javaBean
        Object beanObj=beanClass.newInstance();
        //3、循环set方法数组
        for(Method m:setMethods){
            String methodName=m.getName();
            //3-1、获得方法名
            setMethodNames.add(methodName);
            //3-2、通过方法名推测出属性名
            String name=methodName.substring(3).toLowerCase();
            propertyNames.add(name);
        }
        //3-3、通过request.getParameter(属性名)获得表单数据
        for(String p:propertyNames){
            String value=request.getParameter(p);
            formValues.add(value);
        }
        //3-4、将表单数据转型成为正确的类型,该类型为此set方法的第一个参数的类型
        for(int i=0;i<setMethods.size();i++){
            Method m=setMethods.get(i);
            String type=m.getGenericParameterTypes()[0].toString();
            
            String value=formValues.get(i);
            //判断参数数据类型
//3-5、调用上面实例化的javaBean的此set方法
            if(type.equals("class java.lang.String")){
                m.invoke((T)beanObj, value);
            }else if(type.equals("class java.lang.Integer")){
                m.invoke((T)beanObj, Integer.parseInt(value));
            }
        }
        //4、返回该javaBean
        return (T) beanObj;
    }
    
}

自己用反射写的一个request.getParameter工具类的更多相关文章

  1. Android 分享一个SharedPreferences的工具类,方便保存数据

    我们平常保存一些数据,都会用到SharedPreferences,他是保存在手机里面的,具体路径是data/data/你的包名/shared_prefs/保存的文件名.xml, SharedPrefe ...

  2. 访问github太慢?我写了一个开源小工具一键变快

    前言 GitHub应该是广大开发者最常去的站点,这里面有大量的优秀项目,是广大开发者寻找资源,交友学习的好地方.尤其是前段时间GitHub公布了一项代码存档计划--Arctic Code Vault, ...

  3. 一个python爬虫工具类

    写了一个爬虫工具类. # -*- coding: utf-8 -*- # @Time : 2018/8/7 16:29 # @Author : cxa # @File : utils.py # @So ...

  4. java模板模式项目中使用--封装一个http请求工具类

    需要调用http接口的代码继承FundHttpTemplate类,重写getParamData方法,在getParamDate里写调用逻辑. 模板: package com.crb.ocms.fund ...

  5. 工具类分享之获取Request/Response工具类《RequestContextHolderUtil》

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/aiyaya_/article/details/78975893前言在开发spring web项目时, ...

  6. 自己写的java excel导出工具类

    最近项目要用到excel导出功能,之前也写过类似的代码.因为这次项目中多次用到excel导出.这次长了记性整理了一下 分享给大伙 欢迎一起讨论 生成excel的主工具类: public class E ...

  7. 调用jdbc已经写成的方法----jdbc工具类抽取方式三

    package jdbc_demo3; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.R ...

  8. 自己通过反射写的一个属性copy类

    package com.xxx.beancopier; import java.lang.annotation.Documented; import java.lang.annotation.Elem ...

  9. 自己用的框架写了一个PHP模版解析类

    <?php if(!defined('IS_HEARTPHP')) exit('Access Denied'); /** * template.class.php 模板解析类 * * @copy ...

随机推荐

  1. CoffeeRobotTeam项目组报告

    一.小组分工 模块 任务 责任人 备注 报告 需求分析 熊振威 功能分析 熊振威 项目报告 熊振威 人机界面 秦勤.洪超 单元测试 姜进.张文强 机器人代码 机器人类 徐意.余拥军.孙智博 机器人运动 ...

  2. How to Build FFmpeg for Android

    http://www.roman10.net/how-to-build-ffmpeg-for-android/ ffmpeg is an open-source platform for record ...

  3. codeforces 161D Distance in Tree 树形dp

    题目链接: http://codeforces.com/contest/161/problem/D D. Distance in Tree time limit per test 3 secondsm ...

  4. 【转载】Mybatis多参数查询映射

    转载地址:http://www.07net01.com/zhishi/402787.html 最近在做一个Mybatis的项目,由于是接触不久,虽然看了一下资料,但在实际开发中还是暴 露了很多问题,其 ...

  5. Poj 1255 覆盖的面积 2014-07-28 12:29 116人阅读 评论(0) 收藏

    覆盖的面积 Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Sub ...

  6. 从Theano到Lasagne:基于Python的深度学习的框架和库

    从Theano到Lasagne:基于Python的深度学习的框架和库 摘要:最近,深度神经网络以“Deep Dreams”形式在网站中如雨后春笋般出现,或是像谷歌研究原创论文中描述的那样:Incept ...

  7. aspx文件、aspx.cs文件、aspx.designer.cs文件之讲解

    .aspx文件:(页面)书写页面代码.存储的是页面design代码.只是放各个控件的代码,处理代码一般放在.cs文件中. .aspx.cs文件:(代码隐藏页)书写类代码.存储的是程序代码.一般存放与数 ...

  8. 《JavaScript DOM编程艺术》

    第2章JS语法关联数组在为新元素给出下标时,不必局限于整数数字.数组下标可以是字符串逻辑与&&只有两个操作数都是true时结果才为true逻辑或||只有两个操作数都是false时结果才 ...

  9. YTKNetwork

    YTKNetwork 是猿题库 iOS 研发团队基于 AFNetworking 封装的 iOS 网络库,其实现了一套 High Level 的 API,提供了更高层次的网络访问抽象. YTKNetwo ...

  10. Unity3D开发Windows Store应用程序 注意事项

    原地址:http://blog.csdn.net/jbjwpzyl3611421/article/details/12704491 针对最近在移植window store项目中遇到的问题,我整理了官方 ...