【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!

转载于:https://www.cnblogs.com/jiangbei/p/8417568.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值