BeanUtils.copyProperties()使用详解+在不同包的区别

Posted 来老铁干了这碗代码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了BeanUtils.copyProperties()使用详解+在不同包的区别相关的知识,希望对你有一定的参考价值。

一. 两个包下的BeanUtils.copyProperties对比


BeanUtils是开发中常用到的工具类。
而获取这一工具类常用的方法有两种

  • org.springframework.beans.BeanUtils
  • org.apache.commons.beanutils.BeanUtils

以上两个包皆可获取

不同的包中BeanUtils的方法使用是不一样的,接下来就对这两个包中的copyProperties方法进行对比。

先来看一下这两个包中的,通过copyProperties方法的定义:

//org.springframework.beans.BeanUtils
public static void copyProperties(Object source, Object target)....

//org.apache.commons.beanutils.BeanUtils
public static void copyProperties(Object dest,Object orig)....

可见,在org.springframework.beans.BeanUtils包下的copyProperties第一个参数是被copy的对象,而org.apache.commons.beanutils.BeanUtils中正好相反,不要弄混。

二. 作用和区别


1、两种包引入的方法都是浅拷贝。 关于深浅拷贝的解析:https://blog.csdn.net/weixin_43899069/article/details/121338043

2、使用org.apache.commons.beanutils.BeanUtils进行copy对象时,被copy的对象(source/orig)中包含的字段目标对象(target/dest)必须包含,可以有其他的多于字段,类型可以不相同,但字段名称必须一致;org.springframework.beans.BeanUtils中的没有这个限制。

简而言之,二者区别不大,但org.springframework.beans.BeanUtils更吊一些。

以上是关于BeanUtils.copyProperties()使用详解+在不同包的区别的主要内容,如果未能解决你的问题,请参考以下文章

BeanUtils.copyProperties的用法

BeanUtils.copyProperties的用法

关于BeanUtils.copyProperties()用法和区别

使用 BeanUtils.copyProperties 复制特定字段?

BeanUtils.copyProperties VS PropertyUtils.copyProperties

Spring 之 BeanUtils.copyProperties(...) 源码简读