@[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只是實現了淺複製,這樣存在一個風險就是通過該方法複製的兩個對象中的屬性會引用相同的地址,一個對象對屬性進行更改,另一個對象的屬性也同時會被更改,這是我們在使用中需要注意的地方。