java BeanUtils.copyProperties() 复制对象属性

@[TOC](java 使用BeanUtils.copyProperties() 复制对象属性)

需求背景

这里有A对象和B对象两个具有很多相同属性的JavaBean,通过get、set方法一个一个属性的赋值会非常麻烦,这里就需要用到BeanUtils.copyProperties(source,target);复制A对象属性到B对象中。
代码实现
其中SeasonChapterTemp与SeasonChapter属性名称字段完全一样的

	public static void main(String[] args) {
		SeasonChapterTemp sct = new SeasonChapterTemp();
		sct.setChapterName("会计基础");
		sct.setChapterOrder("第一章");
		sct.setSequence(3);
		System.out.println("SeasonChapterTemp-first:"+sct.getChapterName()+"-"+sct.getChapterOrder());

		SeasonChapter sc = new SeasonChapter();
		BeanUtils.copyProperties(sct,sc);
		System.out.println("SeasonChapter-first:"+sc.getChapterName()+"-"+sc.getChapterOrder());

		sc.setChapterOrder("第三章");
		System.out.println("SeasonChapterTemp-second:"+sct.getChapterName()+"-"+sct.getChapterOrder());
		System.out.println("SeasonChapter-second:"+sc.getChapterName()+"-"+sc.getChapterOrder());

	}

运行结果

符合我们的预期,对SeasonChapter 对象的属性值更改不影响SeasonChapterTemp 的对应属性值。

**注:**通过BeanUtils.copyProperties对两个对象进行复制只是将两个对象的属性引用进行了复制,也就是说BeanUtils.copyProperties只是实现了浅复制,这样存在一个风险就是通过该方法复制的两个对象中的属性会引用相同的地址,一个对象对属性进行更改,另一个对象的属性也同时会被更改,这是我们在使用中需要注意的地方。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn565973850

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值