BeanUtils.copyProperties

2017-08-12  本文已影响0人  不将就51y

最近经常遇到有两个对象的大部分属性是相同的,之前是自己做的转换,今天发现有对象转换的工具类,事半功倍,常用的有如下三类:

一、org.apache.commons.beanutils.BeanUtils.copyProperties

public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException {
BeanUtilsBean.getInstance().copyProperties(dest, orig);
}

二、org.springframework.beans.BeanUtils.copyProperties:

public static void copyProperties(Object source, Object target) throws BeansException {
copyProperties(source, target, (Class)null, (String[])null);
}

三、org.apache.commons.beanutils.PropertyUtils.copyProperties

public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
PropertyUtilsBean.getInstance().copyProperties(dest, orig);
}

实例分割线

属性和类型的值都相同时,三者皆可以使用,但是遇到类型不一致时,转换就有问题了。
CsSettlementBill.java

private String remark;
private Date startDate;

转换成CsSettlementBillDto.java

private String remark;
private String startDate;

测试类

@Test
public void testApacheBeanUtilsCopyProperties() throws
InvocationTargetException, IllegalAccessException {
CsSettlementBill settlementBill = new CsSettlementBill();
settlementBill.setRemark("22133");
settlementBill.setStartDate(new Date());
CsSettlementBillDto dto = new CsSettlementBillDto();
org.apache.commons.beanutils.BeanUtils.copyProperties(dto, settlementBill); dto.setStartDate(com.suning.epp.pu.common.util.DateUtil.dateToString(settlementBill.getStartDate(), DATEFORMATE_YYYYMMDD));
System.out.println(dto);
}

运行结果正确
{"amount":"10000","startDate":"20170812"}

@Test
public void testSpringBeanUtilsCopyProperties() {
CsSettlementBill settlementBill = new CsSettlementBill();
settlementBill.setRemark("22133");
settlementBill.setStartDate(new Date());
CsSettlementBillDto dto = new CsSettlementBillDto();
org.springframework.beans.BeanUtils.copyProperties(settlementBill, dto);
System.out.println(dto);
}

运行异常,提示信息如下:
Could not copy properties from source to target; nested exception is java.lang.IllegalArgumentException: argument type mismatch

@Test
public void testApachePropertyUtilsCopyProperties() throws IllegalAccessException, NoSuchMethodException,InvocationTargetException {
CsSettlementBill settlementBill = new CsSettlementBill();
settlementBill.setRemark("22133");
settlementBill.setStartDate(new Date());
CsSettlementBillDto dto = new CsSettlementBillDto();
org.apache.commons.beanutils.PropertyUtils.copyProperties(dto, settlementBill);
System.out.println(dto);
}

运行异常,提示信息如下:
argument type mismatch - had objects of type "java.util.Date" but expected signature "java.lang.String"

总之,在属性和类型都相同时三者皆可使用,属性相同类型不同时经过测试只能使用org.apache.commons.beanutils.BeanUtils.copyProperties,另外需要注意source和target参数的位置。

上一篇下一篇

猜你喜欢

热点阅读