使用 BeanCopier 複製對象

來源:互聯網
上載者:User

標籤:

Cglib是一款比較底層的操作java位元組碼的架構。

BeanCopier是一個工具類,可以用於Bean對象內容的複製。

複製Bean對象內容的方法有很多,比如自己手動get set ,或者使用PropertyUtils或者使用BeanUtils

 

BeanCopier與 PropertyUtils 、BeanUtils的不同在於:

PropertyUtils 和 BeanUtils 使用的是反射機制來完成屬性的複製。

而BeanCopier 的原理是通過位元組碼動態產生一個類,這個裡面實現get 和 set方法。(效能和對象直接調用set一樣)

BeanCopier 唯一的花銷是產生動態類上,但是產生的後的象可以自己儲存起來反覆使用。

根據網上的資料 BeanCopier的效能是PropertyUtils (apache-common)的500倍。 PropertyUtils的效能是BeanUtils(apache-common)的2倍。

 

以下是使用例子

import net.sf.cglib.beans.BeanCopier;public class BeanCopierTest {public static void main(String[] args) {Bean1 bean1 = new Bean1();Bean2 bean2 = new Bean2();bean1.setValue("hello");BeanCopier copier = BeanCopier.create(Bean1.class, Bean2.class, false);copier.copy(bean1, bean2, null);System.out.println(bean2.getValue());}static class Bean1 {private String value;public String getValue() {return value;}public void setValue(String value) {this.value = value;}}static class Bean2 {private String value;public String getValue() {return value;}public void setValue(String value) {this.value = value;}}}

 

注意事項:BeanCopier在複製的時候使用get和set方法了。如果方法定義不嚴格,會造成複製的對象屬性值不正確。

 

使用 BeanCopier 複製對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.