适用范围:当我们在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. LeetCode-Largest Divisble Subset

    Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of ...

  2. 团队开发——Alpha版总结会议

    本组目前存在的问题: 1.在选题的时候,题目选的比较有难度,造成后期工作量较大,实现有难度(未能正确估计项目的难度). 2.最初规划时,设计的功能较多,但是技术水平达不到,导致目前完成功能较少. 3. ...

  3. jQuery Dialog弹出层对话框插件

    Dialog.js的相关注释已经添加,可以按照注释,进行相关样式的修改,适用于自定义的各个系统! dialog.js /** * jQuery的Dialog插件. * * @param object ...

  4. 【BZOJ】【1027】【JSOI2007】合金

    计算几何/凸包/Floyd Orz rausen大爷太强辣 计算几何题目果然不会做>_> 这个题……虽然他给了3个坐标,但实际上是个二维的计算几何题= =因为第三维坐标可以直接用前两维坐标 ...

  5. Effective Java总结

    规则1. 用静态工厂方法代替构造器 例子: public class Example { } public class StaticFactory { //valueOf/Of/getInstance ...

  6. c++ assert

    #include<iostream> #include <assert.h> using namespace std; int main() { ; assert(a == ) ...

  7. 在C++的类中,普通成员函数不能作为pthread_create的线程函数,如果要作为pthread_create中的线程函数,必须是static

    在C++的类中,普通成员函数不能作为pthread_create的线程函数,如果要作为pthread_create中的线程函数,必须是static ! 在C语言中,我们使用pthread_create ...

  8. Unity Texture 2D Compress

    测试了一下 unity 图片 对 apk 的影响. 上两种测试环境    1024 * 1024     带 alpha的话 默认压缩就是RBA 16bit就是2M     不带的话就是 etc 的话 ...

  9. vi/vim使用指北 ---- Learning the vi and Vim Editors 读书 笔记

    vi/vim作为liux系统下最强大,最流行的文本编辑器之一.边看<Learning the vi and vim Editor>边学习vim,顺便做写简单的笔记,供以后查询. 没看这本书 ...

  10. 九个衡量 Rails 应用性能的小方法

    你有个绝佳的商业创意,日复一日地将它完善丰满起来.后来,你雇了一群天赋异禀的开发者.Web 设计师和用户体验专家,他们用一种非常棒的框架--Ruby on Rails 帮你实现长久以来的梦想. 你的网 ...