【commons】Bean工具類——commons-beanutils之BeanUtils


一、起步

  引入依賴:

<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.8.3</version>
</dependency>

  當然,一般可能項目中不會需要單獨引入這個依賴,可能其他依賴自動引入了此包,請先檢查,避免重復引入!

二、開始

  文檔http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.3/apidocs/org/apache/commons/beanutils/BeanUtils.html

  參考隨筆https://www.cnblogs.com/vmax-tam/p/4159985.html

  1.常用方法   

 copyProperties(Object dest, Object orig) Copy property values from the origin bean to the destination bean for all cases where the property names are the same. copyProperty(Object bean, String name, Object value) Copy the specified property value to the specified destination bean, performing any type conversion that is required. populate(Object bean, Map<String,? extends Object> properties) Populate the JavaBeans properties of the specified bean, based on the specified name/value pairs.

  2.代碼演示

    不再(tou)贅述(lan),查看網友示例https://www.cnblogs.com/vmax-tam/p/4159985.html

  3.注意點(引用自網友)

  (淺拷貝)  

  關於bean復制,如果屬性較少,建議直接寫個方法完成get/set即可。如果屬性較多,可以自己采用反射實現一個滿足自己需要的工具類,或者使用spring的那個beanutils類,不建議使用commons-beanutils包中的那個BeanUtils類,剛看了下,這個類對於內部靜態類的對象復制也會出現問題,檢驗太復雜了,常會出現一些詭異的問題。畢竟我們bean復制一般就是簡單的屬性copy而已。

而且,由於這些BeanUtils類都是采用反射機制實現的,對程序的效率也會有影響。因此,慎用BeanUtils.copyProperties!!!

  4.對比與拓展

    如果有Date等類型,請參考spring的BeanUtilshttps://www.cnblogs.com/dongfangshenhua/p/7099970.html

    如果引入了hutool依賴,推薦hutool的BeanUtils!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM