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只是实现了浅复制,这样存在一个风险就是通过该方法复制的两个对象中的属性会引用相同的地址,一个对象对属性进行更改,另一个对象的属性也同时会被更改,这是我们在使用中需要注意的地方。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章