标签:
适用范围:当我们在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工具类
标签:
原文地址:http://www.cnblogs.com/firstdream/p/4738155.html