java對象拷貝——PropertyUtils.copyProperties()用法和效能

來源:互聯網
上載者:User

BeanUtils提供對Java反射和自省API的封裝。其主要目的是利用反射機制對JavaBean的屬性進行處理。一個JavaBean通常包含了大量的屬性,很多情況下,對JavaBean的處理導致大量get/set代碼堆積,增加了代碼長度和閱讀代碼的難度。

使用PropertyUtils.copyProperties()拷貝一個bean中的屬性到另一個bean中,第一個參數是目標bean,第二個參數是源bean。

  例一Book srcBook = new Book();
srcBook.setName("Java");
Book destBook = new Book();
PropertyUtils.copyProperties(destBook, srcBook);
System.out.println(destBook.getName());   例二(對刪除的資料進行備份)Student s = new Student();s.setName("xy")................StudentBak sbak = new StudentBak();PropertyUtils.copyProperties(sbak , s);StudentBakDao.save(sbak);StudentDao.delete(s); 沒有PropertyUtils.copyProperties,我們只能StudentBak sbak = new StudentBak();sbak.setName(s.getName);.........................如果有是十個屬性,我們不是累呆了。

該方法做對象的拷貝很方便,但是它的效能問題相當差 看下面的測試代碼:
public class A{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

import org.apache.commons.beanutils.PropertyUtils;
public class PropertyUtilsTest
{
public static void main(String []args)
{

 

普通的copy,每個欄位拷貝

A a1 = new A();
a1.setName("wang");

A a2 = new A();
long b = new java.util.Date().getTime();
a2.setName(a1.getName());

long e = new java.util.Date().getTime();
System.out.println("time1="+(e-b));
 try{
PropertyUtils.copyProperties方法copyA a3 = new A();
b = new java.util.Date().getTime();
PropertyUtils.copyProperties(a3, a1);
e = new java.util.Date().getTime();
System.out.println("time2="+(e-b));
}  catch (Exception e1){
e1.printStackTrace();
}
}
}

最後輸出:
time1=0
time2=265 兩種方法時間差那麼多!  原帖地址:http://hi.baidu.com/dobodo/blog/item/f741897be7a0a1f80bd187ef.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.