public class BeanUtils {
//第一种:/// 使用到反射的地方
//把request 的值 转换成对象并返回
public static <T> T transBean(Class<T> clazz, HttpServletRequest request) {
T entity = null;
try {
entity = clazz.newInstance();
}
catch (Exception e) {
e.printStackTrace();
}
Enumeration<String> names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String value = request.getParameter(name);
try {
//使用属性描述器获得该属性的类型
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, clazz);
//得到了属性的类型. 为了转换 基本数据类型 和日期类型,等等非字符串类型
Class aClassType = propertyDescriptor.getPropertyType();
Method method = propertyDescriptor.getWriteMethod();
if (aClassType.equals(Integer.class)) {//以此类推
method.invoke(entity, Integer.parseInt(value));
}
else {
method.invoke(entity, value);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
return entity;
}
===========================================================================================
//第二种 使用反射的地方
//通过反射直接给对象赋值
public static <T> void transBean(Object obj) {
setVal(obj,"setCreateTime","创建时间");
setVal(obj,"setCreateUser","创建人");
setVal(obj,"setUpdateTime","修改时间");
setVal(obj,"setUpdateUser","修改人");
}
public static void setVal(Object obj, String methodName, String val) {
Class clazz = obj.getClass();
Method method = null;
try {
method = clazz.getMethod(methodName, String.class);
method.invoke(obj, val);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public class User implements Serializable {
private String name;
private Integer age;
private String createTime;
private String createUser;
private String updateTime;
private String updateUser;
//省略 get set 方法 ...,不在这里贴了
}