使用反射模拟struts2属性注入功能

1.在项目开发中,如果没有使用框架进行数据绑定与封装,则可能会写大量的类似下面的代码:

String value=request.getParameter("v");
if(null!=value){
obj.setValue(value);
}

所以有必要自己实现一个满足实际需求的自动注入表单信息到数据模型中的功能。

实现代码:

package com.cml.model;


import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;


public class BindRequest
{
// 默认日期格式
private static final String DATE_FORMAT = "yyyy-MM-dd";
private SimpleDateFormat format;


public BindRequest(String f)
{
format = new SimpleDateFormat(f);
}


public BindRequest()
{
this(DATE_FORMAT);
}


@SuppressWarnings("unchecked")
public <T> T bindFromRquest(Class<?> clazz, HttpServletRequest request)
throws Exception
{

Object instance = clazz.newInstance();
// 获取请求的所有参数信息
Map<String, String> parameters = request.getParameterMap();


Iterator<String> it = parameters.keySet().iterator();


while (it.hasNext())
{
// 获取表单参数中的name
String key = it.next();
// 获取表单参数中的value
String value = request.getParameter(key);
// 获取get方法
Method getMethod = clazz.getDeclaredMethod(this.initGetMethod(key),
null);
// 获取参数返回的类型
Class type = getMethod.getReturnType();


Method method = clazz.getDeclaredMethod(this.initSetMethod(key),
type);


if (type == String.class)
{
method.invoke(instance, value);
} else if (type == int.class || type == Integer.class)
{
method.invoke(instance, Integer.parseInt(value));


} else if (type == long.class || type == Long.class)
{
method.invoke(instance, Long.parseLong(value));


} else if (type == float.class || type == Float.class)
{
method.invoke(instance, Float.parseFloat(value));


} else if (type == double.class || type == Double.class)
{
method.invoke(instance, Double.parseDouble(value));


} else if (type == Date.class)
{
method.invoke(instance, format.parse(value));
}
}


return (T) instance;
}


public String initSetMethod(String field)
{
return "set" + field.substring(0, 1).toUpperCase() + field.substring(1);
}


public String initGetMethod(String field)
{
return "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
}
}

这个类可以满足大部分需求了,如果对象中有数据或集合类型,则需要自己修改部分即可!

posted @ 2014-04-06 12:27  小小架构师  阅读(149)  评论(0编辑  收藏  举报