BeanUtils
大约 1 分钟languagejava
复制bean
import org.springframework.beans.BeanUtils;
PlanBill repairedPlan = new PlanBill();
BeanUtils.copyProperties(planBill,repairedPlan);
Map 2 Bean
下面方法遇到日期类型的属性会报错
// 调用示例
PlanBill planBill = new PlanBill();
transMap2Bean(map对象,planBill);
// 本方法遇到日期类型的属性会报错
public static Object transMap2Bean(Map<String,Object> map,Object obj){
try{
//1.获取bean信息
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor prop: properties) {
String key = prop.getName();
if(map.containsKey(key) && map.get(key) != null){
Object value = map.get(key);
Method setMethod = prop.getWriteMethod();
setMethod.invoke(obj,value);
}
}
}catch(Exception e){
e.printStackTrace();
}
return obj;
}
使用下面方法更通用
import org.apache.commons.beanutils.BeanUtils;
// 调用方法:
// PlanBill planBill = new PlanBill();
// Map<String,Object> planBillMap = (Map<String, Object>) params.get("planBill");
// populateBeanFromMap(planBill,planBillMap);
// 遇到日期类型按照 yyyy-MM-dd 样式转换,如果有多种样式的日期属性
// 则需要通过另外的参数指定每个属性转换时使用的日期格式
// 如果转换后的对象 bean 中包含其他模型对象,则会保留为原始的 Map<String,Object> 类型
// 所以要另外手动再次转换为 bean 类型
public static void populateBeanFromMap(Object bean, Map<String, Object> properties) throws Exception {
for (Map.Entry<String, Object> entry : properties.entrySet()) {
String propertyName = entry.getKey();
Object propertyValue = entry.getValue();
// 解析日期类型
if (isDateType(bean, propertyName)) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(propertyValue.toString());
} catch (ParseException e) {
throw new Exception("日期格式错误:" + propertyValue, e);
}
BeanUtils.setProperty(bean, propertyName, date);
} else {
BeanUtils.setProperty(bean, propertyName, propertyValue);
}
}
}
/**
* 判断指定JavaBean类中指定属性名是否为日期类型
*/
private static boolean isDateType(Object bean, String propertyName) {
try {
return bean.getClass().getDeclaredField(propertyName).getType() == Date.class;
} catch (NoSuchFieldException e) {
return false;
}
}
