适用范围:当我们在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. 闹钟类app构想

    NABC--闹钟app N:我们打算针对那些易健忘的人来制作一款闹钟功能的记事本,具来说服务的对象有很多:有健忘的人,还有情侣,北漂的人及其父母(...),常年见不到亲人(双方),后期我们若提前完成基 ...

  2. 初学MFC

    学习使用MFC搭建界面.尝试使用MFC搭建了一个简单的基于对话框的计算器界面,包括模态对话框.非模态对话框.向导对话框等. // MFCApplicationAddDlg.h : 头文件 // #pr ...

  3. struts1 和 struts2中Action什么时候实例化

    精帖1:http://blog.csdn.net/lfsf802/article/details/7277013 精帖1:http://blog.csdn.net/wmj2003/article/de ...

  4. DWR推送技术

    “服务器推送技术”(ServerPushing)是最近Web技术中最热门的一个流行术语.它是继“Ajax”之后又一个倍受追捧的Web技术.“服务器推送技术”最近的流行跟“Ajax ”有着密切的关系. ...

  5. 【BZOJ】【1028】【JSOI2007】麻将

    暴力/模拟 $n\leq400$,嗯……这是一个很小的数据范围= = 判断一副牌是不是听牌并求出听什么牌太麻烦了,干脆我们直接判是不是胡牌好了~ 枚举胡的是哪张牌,然后判一下加上这张牌后是否能胡. 算 ...

  6. Winform跨线程操作界面的策略

    BeginInvoke(new ThreadStart(() => toolStripButton1.Text = "aaa")); 1.非跨线程操作和部分跨线程get不会引 ...

  7. TJU 4087. box

    题目:Tuhao and his two small partners participated in the tournament.But in the end, they lost the cha ...

  8. HTML5 Cheat sheet PNG帮助手册(标签、事件、兼容)

    HTML5 Cheat sheet PNG帮助手册(标签.事件.兼容) 1.HTML5标签 2.HTML5事件 3.HTML5兼容 最新HTML5手册资料请参考:http://www.inmotion ...

  9. Python:异常处理

    Python 是面向对象的语言,所以程序抛出的异常也是类. 一.常见的异常类 NameError:尝试访问一个没有申明的变量 ZeroDivisionError:除数为 0 SyntaxError:语 ...

  10. 8086CPU各寄存器的用途

    8086 有14个16位寄存器,这14个寄存器按其用途可分为(1)通用寄存器.(2)指令指针.(3)标志寄存器和(4)段寄存器等4类. 1.通用寄存器有8个, 又可以分成2组,一组是数据寄存器(4个) ...