为了方便将表单提交上来的参数和map集合中的数据快速封装成对象,利用java的内省机制编写该方法。话不多说直接上代码。
public class BeanUtils {
private BeanUtils() {
}
/**
* @Description 将map集合中的值装入实体对象
* @param bean 实体对象
* @param map 值
* @throws Exception
*/
public static void populate(Object bean, Map<String, ?> map) throws Exception {
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : descriptors) {
String name = property.getName();
Method method2 = property.getWriteMethod();
Object object = map.get(name);
if (object instanceof String[]) { //表单提交上来的请求参数 value 值数组类型所以转换 取第一个值
String[] string = (String[]) object;
String value = string[0];
change(bean, property, method2, value);
} else {
change(bean, property, method2, object + "");
}
}
}
private static void change(Object bean, PropertyDescriptor property, Method method2, String value)
throws IllegalAccessException, InvocationTargetException, ParseException {
//取出字段属性
Class<?> type = property.getPropertyType();
String typename = type.getName();
switch (typename) {
case "java.lang.String":
method2.invoke(bean, value + "");
break;
case "java.lang.Integer":
method2.invoke(bean, Integer.parseInt(value + ""));
break;
case "java.lang.Double":
method2.invoke(bean, Double.parseDouble(value + ""));
break;
case "java.lang.Float":
method2.invoke(bean, Double.parseDouble(value + ""));
break;
case "java.util.Date":
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd");
Date date = null;
try {
date = format.parse(value + "");
} catch (ParseException e) {
date = format2.parse(value + "");
}
method2.invoke(bean, date);
break;
}
}
}