1:以下两个不同的包都存在BeanUitls.copyProperties方法
org.springframework.beans.BeanUtils.copyProperties(Object source, Object target) throws BeansException
org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest, Object orig)throws IllegalAccessException, InvocationTargetException
2:测试属性名相同类型不同的两个类,执行BeanUtils.copyProperties方法
调用org.springframework.beans.BeanUtils.copyProperties,如果source与target中存在属性名相同类型不同的情况,则target中对应的属性值为null
调用org.apache.commons.beanutils.BeanUtils.copyProperties,如果dest与orig中存在属性名相同类型不同的情况,则会抛出IllegalArgumentException异常
public class WoType {
private Long id;
private String name;
private WoType Parent;
@Override
public String toString() {
return "WoType [id=" + id + ", name=" + name + ", Parent=" + Parent + "]";
}
}
public class WoTypeVo {
private Long id;
private String name;
private WoTypeVo Parent;
@Override
public String toString() {
return "WoTypeVo [id=" + id + ", name=" + name + ", Parent=" + Parent + "]";
}
}
初始化WoType对象
@Before
public void before() {
woType=new WoType();
woType.setId(100L);
woType.setName("收货地址错误");
//封装parent
WoType parent=new WoType();
parent.setId(101L);
parent.setName("快递问题");
woType.setParent(parent);
}
测试org.springframework.beans.BeanUtils.copyProperties:
@Test
public void testSpringBeanUtils() {
WoTypeVo woTypeVo=new WoTypeVo();
org.springframework.beans.BeanUtils.copyProperties(woType, woTypeVo);
System.out.println(woType.toString()+" "+woTypeVo.toString());
}
结论:WoType [id=100, name=收货地址错误, Parent=WoType [id=101, name=快递问题, Parent=null]] WoTypeVo [id=100, name=收货地址错误, Parent=null]
测试org.apache.commons.beanutils.BeanUtils.copyProperties:
@Test
public void testApacheBeanUtils() {
WoTypeVo woTypeVo=new WoTypeVo();
try {
org.apache.commons.beanutils.BeanUtils.copyProperties(woTypeVo, woType);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(woType.toString()+" "+woTypeVo.toString());
}
结论:抛出IllegalArgumentException异常