/*
*
* 为了保证原bean中的数据不为空,需要自己设置转换器。
* 当执行BeanUtils.copyProperties(dest, src);时会首先去调用转换器(Converter接口的实现方法convert),然后再执行转换.
*/
public static void copyBean(Object src, Object dest) {
try{
//注册日期转换器 frombean-->birthday="" user-birhday=null
ConvertUtils.register(new Converter(){
public Object convert(Class type, Object value) { //198a
if(value==null){
return null;
}
String s = (String)value;
if(s.trim().equals("")){
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(s);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}, Date.class);
//实现bean的拷呗
BeanUtils.copyProperties(dest, src);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
用BeanUtils类实现bean的拷贝
最新推荐文章于 2023-08-14 06:46:10 发布
本文介绍了一种在Java中自定义Bean属性复制的方法,通过实现转换器接口来处理空值和日期格式转换的问题,确保了源Bean的数据在复制过程中得到正确的处理。
1050

被折叠的 条评论
为什么被折叠?



