BeanUtils.copyProperties方法复制不同对象间的属性值

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异常
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值