适用范围:当我们在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. nscd

    作用: Nscd is a daemon that provides a cache for the most common name service requests 可以缓存passwd,grou ...

  2. IE9兼容性视图与IE9标准视图

    如果你使用的是IE9,那么按下F12键就会出现开发者工具,上面有两个下拉菜单:浏览器模式和文档模式.那么什么是浏览器模式?什么又是文档模式?二者有何区别? 浏览器模式用于切换IE针对该网页的默认文档模 ...

  3. modernizr.js

    1.判断浏览器是否支持 h5 if(Modernizr.canvas){ alert(123); }else{ alert(321); } 2.判断浏览器是否支持 canvas function su ...

  4. 【Java】Eclipse导出jar包与javadoc

    1.导出jar包 2.导出javadoc 3.jar包添加javadoc 4.出错解决 参考资料: http://www.cnblogs.com/cyh123/p/3345889.html http: ...

  5. Spring MVC 入门教程示例 (一)

    今天和大家分享下  Spring MVC  入门教程 首先还是从 HelloWorld  web 工程开始 -------------------------- 1.首先创建一个Maven Web工程 ...

  6. AVFoundation的使用

    AVFoundation的使用 2013-05-03 14:50:21|  分类: iphone_dev_note|举报|字号 订阅         相机相关应用一般会用到AVFoundation. ...

  7. org.codehaus.xfire.XFireRuntimeException: Could not invoke service.. Server returned error code = 404 for URI.. Check server logs for details

    严重: Servlet.service() for servlet jsp threw exceptionorg.codehaus.xfire.XFireRuntimeException: Could ...

  8. Sea.js入门

    本文只是seajs的入门贴.要详细了解,请看GitHub主页上的相关链接,精彩不断,精选几篇: 前端模块化开发的价值 前端模块化开发的历史 ID和路径匹配原则 与RequireJS的异同 模块的加载启 ...

  9. aspx页面生成html

              /// <summary>         /// aspx生成Html         /// </summary>         /// <pa ...

  10. 理解Linux系统负荷[转]

    一.查看系统负荷 在Linux系统中,我们一般使用uptime命令查看(w命令和top命令也行).(另外,它们在苹果公司的Mac电脑上也适用.)   二.一个类比 我们不妨把这个CPU想象成一座大桥, ...