利用反射机制写的一个工具类,只做了String Integer Float类的自动封装,其他类请自行添加,注释很全
有问题可以评论留言,大家一起讨论
调用实例
Business business = WebUtils.request2Bean(request,Business.class);
WebUtils.java
import com.neusoft.elm.entity.Business;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Enumeration;
public class WebUtils {
public static <T> T request2Bean(HttpServletRequest request, Class<T> clazz) {
try {
T bean = clazz.newInstance();
Enumeration<String> e = request.getParameterNames();
while (e.hasMoreElements()) {
String name = e.nextElement();
String value = request.getParameter(name);
if (value != null && value.trim().length() != 0) {
setProperty(bean, name, value);
}
}
return bean;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static <T> void setProperty(T bean, String name, String value) {
Class<?> aClass = bean.getClass();
Field[] fields = aClass.getDeclaredFields();
try {
for (Field field : fields) {
if (field.getGenericType().toString().equals(String.class.toString())) {
if (field.getName().equals(name)){
Method m = bean.getClass().getMethod(getMethodName(name), field.getType());
m.invoke(bean, value);
}
}
if (field.getGenericType().toString().equals(Integer.class.toString())) {
if (field.getName().equals(name)){
Method m = bean.getClass().getMethod(getMethodName(name), field.getType());
m.invoke(bean, Integer.parseInt(value));
}
}
if (field.getGenericType().toString().equals(Float.class.toString())) {
if (field.getName().equals(name)){
Method m = bean.getClass().getMethod(getMethodName(name), field.getType());
m.invoke(bean, Float.parseFloat(value));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getMethodName(String name) {
return "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
}
public static void main(String[] args) {
Business business = new Business();
setProperty(business, "remarks", "succes");
setProperty(business, "orderTypeId", "1");
setProperty(business, "deliveryPrice", "1.10");
System.out.println(business);
}
}
|