public class BeanUtilEx extends BeanUtils {
private BeanUtilEx() {
}
static {
//注册sql.date的转换器,即允许BeanUtils.copyProperties时的源目标的sql类型的值允许为空
ConvertUtils.register(new SqlDateConverter(), java.util.Date.class);
//注册util.date的转换器,即允许BeanUtils.copyProperties时的源目标的util类型的值允许为空
ConvertUtils.register(new DateConverter(), java.util.Date.class);
}
public static void copyProperties(Object target, Object source) throws
InvocationTargetException, IllegalAccessException {
org.apache.commons.beanutils.BeanUtils.copyProperties(target, source);
}
}
public class DateConverter implements Converter {
public Object convert(Class arg0, Object arg1) {
String p = (String)arg1;
if(p== null || p.trim().length()==0){
return null;
}
try{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df.parse(p.trim());
}
catch(Exception e){
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.parse(p.trim());
} catch (ParseException ex) {
return null;
}
}
}
}