import org.apache.commons.beanutils.BeanUtils;
当使用BeanUtils时,
- java.util.Date类型转换会出现异常;
- java.lang.Integer(当为null的时候)会默认 转为0值,出现一些意外的结果
解决方案,对BeanUtils进行拓展:
import org.apache.commons.beanutils.Converter; import java.lang.reflect.InvocationTargetException; import java.text.SimpleDateFormat; import java.util.Date; public class BeanUtilsExt extends BeanUtils { static { ConvertUtils.register(new DateConvert(), java.util.Date.class); ConvertUtils.register(new IntegerConvert(), java.lang.Integer.class); } public static void copyProperties(Object dest, Object orig) { try { BeanUtils.copyProperties(dest, orig); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InvocationTargetException ex) { ex.printStackTrace(); } } } class DateConvert implements Converter { public Object convert(Class arg0, Object arg1) { Date d = (Date) arg1; if (d == null) { return null; } try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return sdf.parse(sdf.format(d)); } catch (Exception e) { return null; } } } class IntegerConvert implements Converter { public Object convert(Class arg0, Object arg1) { Integer d = (Integer) arg1; if (d == null) { return null; } return d; } }