自己用反射写的一个request.getParameter工具类
适用范围:当我们在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工具类的更多相关文章
- Android 分享一个SharedPreferences的工具类,方便保存数据
我们平常保存一些数据,都会用到SharedPreferences,他是保存在手机里面的,具体路径是data/data/你的包名/shared_prefs/保存的文件名.xml, SharedPrefe ...
- 访问github太慢?我写了一个开源小工具一键变快
前言 GitHub应该是广大开发者最常去的站点,这里面有大量的优秀项目,是广大开发者寻找资源,交友学习的好地方.尤其是前段时间GitHub公布了一项代码存档计划--Arctic Code Vault, ...
- 一个python爬虫工具类
写了一个爬虫工具类. # -*- coding: utf-8 -*- # @Time : 2018/8/7 16:29 # @Author : cxa # @File : utils.py # @So ...
- java模板模式项目中使用--封装一个http请求工具类
需要调用http接口的代码继承FundHttpTemplate类,重写getParamData方法,在getParamDate里写调用逻辑. 模板: package com.crb.ocms.fund ...
- 工具类分享之获取Request/Response工具类《RequestContextHolderUtil》
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/aiyaya_/article/details/78975893前言在开发spring web项目时, ...
- 自己写的java excel导出工具类
最近项目要用到excel导出功能,之前也写过类似的代码.因为这次项目中多次用到excel导出.这次长了记性整理了一下 分享给大伙 欢迎一起讨论 生成excel的主工具类: public class E ...
- 调用jdbc已经写成的方法----jdbc工具类抽取方式三
package jdbc_demo3; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.R ...
- 自己通过反射写的一个属性copy类
package com.xxx.beancopier; import java.lang.annotation.Documented; import java.lang.annotation.Elem ...
- 自己用的框架写了一个PHP模版解析类
<?php if(!defined('IS_HEARTPHP')) exit('Access Denied'); /** * template.class.php 模板解析类 * * @copy ...
随机推荐
- 【Evaluate Reverse Polish Notation】cpp
题目: Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are + ...
- mac os 10.10上安装my eclipse显示virtual memory不足,解决方案
mac os 10.10上安装my eclipse显示virtual memory不足,安装失败. 自从把OS 升级到10.10 之后, 各种问题, 安装的时候向导提示提示我们说没有足够的虚拟内存, ...
- HDU 5592 ZYB's Premutation
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=5592 题意: http://bestcoder.hdu.edu.cn/contests/contes ...
- 二分---LIGHTOJ 1062
1062 - Crossed Ladders PDF (English) Statistics Forum Time Limit: 2 second(s) Memory Limit: 32 MB A ...
- 设计模式之策略模式(strategy)
策略模式原理:策略模式和简单工厂模式有点类似,只是简单工厂模式产生的是对象,策略模式产生的是根据对象产生的算法. 代码如下: #include <iostream> #include &l ...
- C++中的RAII机制
http://www.jellythink.com/archives/101 前言 在写C++设计模式——单例模式的时候,在写到实例销毁时,设计的GC类是很巧妙的,而这一巧妙的设计就是根据当对象的生命 ...
- 威胁远胜“心脏出血”?国外新爆Bash高危安全漏洞
这几天Linux用户们可能不能愉快地玩耍了,红帽(Redhat)安全团队昨天爆出一个危险的Bash Shell漏洞.其带来的威胁可能比早前披露的“心脏出血”漏洞更大更强! [OpenSSL心脏出血漏洞 ...
- Linux常用命令大全(转载)
系统信息 arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 dmidecode -q 显示硬件系统部件 - (SMBIOS ...
- .NET4.0下网站应用法度用UrlRewriter.dll重写无后缀路径 (在IIS7.5中的设备办法)
.NET4.0下网站应用法度用UrlRewriter.dll重写无后缀路径 在IIS中新建网站(端标语8111) 直接运行http://localhost:8111/ 设备办法: 二.添加通配符脚本映 ...
- Codeforces Round #246 (Div. 2)——D题
KMP算法,没写出来,完全不理解NEXT数组.现在理解了很多 答案都在程序中 ,不过这个思想真的很神奇, 还有毛语不好,一直没看懂题目,现在懂了, 大概是:S中前缀等于后缀,求其长度,和其在S中出现了 ...