点击上方“方志朋”,选择“设为星标”

回复”666“获取新整理的面试文章

在我们实际项目开发过程中,我们经常需要将不同的两个对象实例进行属性复制,从而基于源对象的属性信息进行后续操作,而不改变源对象的属性信息,比如DTO数据传输对象和数据对象DO,我们需要将DO对象进行属性复制到DTO,但是对象格式又不一样,所以我们需要编写映射代码将对象中的属性值从一种类型转换成另一种类型。

对象拷贝

在具体介绍两种 BeanUtils 之前,先来补充一些基础知识。它们两种工具本质上就是对象拷贝工具,而对象拷贝又分为深拷贝和浅拷贝,下面进行详细解释。

什么是浅拷贝和深拷贝

在Java中,除了 基本数据类型之外,还存在 类的实例对象这个引用数据类型,而一般使用 “=”号做赋值操作的时候,对于基本数据类型,实际上是拷贝的它的值,但是对于对象而言,其实赋值的只是这个对象的引用,将原对象的引用传递过去,他们实际还是指向的同一个对象。而浅拷贝和深拷贝就是在这个基础上做的区分,如果在拷贝这个对象的时候,只对基本数据类型进行了拷贝,而对引用数据类型只是进行引用的传递,而没有真实的创建一个新的对象,则认为是浅拷贝。反之,在对引用数据类型进行拷贝的时候,创建了一个新的对象,并且复制其内的成员变量,则认为是深拷贝。

简单来说:

  • 浅拷贝:对基本数据类型进行值传递,对引用数据类型进行引用传递般的拷贝,此为浅拷贝

  • 深拷贝:对基本数据类型进行值传递,对引用数据类型,创建一个新的对象,并复制其内容,此为深拷贝。

BeanUtils

前面简单讲了一下对象拷贝的一些知识,下面就来具体看下两种 BeanUtils 工具

Apache 的 BeanUtils

首先来看一个非常简单的BeanUtils的例子

publicclass PersonSource {private Integer id;private String username;private String password;private Integer age;// getters/setters omiited
}
publicclass PersonDest {private Integer id;private String username;private Integer age;// getters/setters omiited
}
publicclass TestApacheBeanUtils {public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {//下面只是用于单独测试PersonSource personSource = new PersonSource(1, "pjmike", "12345", 21);PersonDest personDest = new PersonDest();BeanUtils.copyProperties(personDest,personSource);System.out.println("persondest: "+personDest);}
}
persondest: PersonDest{id=1, username='pjmike', age=21}

从上面的例子可以看出,对象拷贝非常简单,BeanUtils最常用的方法就是:

//将源对象中的值拷贝到目标对象//将源对象中的值拷贝到目标对象
public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException {BeanUtilsBean.getInstance().copyProperties(dest, orig);
}

默认情况下,使用org.apache.commons.beanutils.BeanUtils对复杂对象的复制是引用,这是一种浅拷贝

但是由于 Apache下的BeanUtils对象拷贝性能太差,不建议使用,而且在阿里巴巴Java开发规约插件上也明确指出:

Ali-Check | 避免用Apache Beanutils进行属性的copy。

commons-beantutils 对于对象拷贝加了很多的检验,包括类型的转换,甚至还会检验对象所属的类的可访问性,可谓相当复杂,这也造就了它的差劲的性能,具体实现代码如下:

public void copyProperties(final Object dest, final Object orig)throws IllegalAccessException, InvocationTargetException {// Validate existence of the specified beansif (dest == null) {thrownew IllegalArgumentException("No destination bean specified");}if (orig == null) {thrownew IllegalArgumentException("No origin bean specified");}if (log.isDebugEnabled()) {log.debug("BeanUtils.copyProperties(" + dest + ", " +orig + ")");}// Copy the properties, converting as necessaryif (orig instanceof DynaBean) {final DynaProperty[] origDescriptors =((DynaBean) orig).getDynaClass().getDynaProperties();for (DynaProperty origDescriptor : origDescriptors) {final String name = origDescriptor.getName();// Need to check isReadable() for WrapDynaBean// (see Jira issue# BEANUTILS-61)if (getPropertyUtils().isReadable(orig, name) &&getPropertyUtils().isWriteable(dest, name)) {final Object value = ((DynaBean) orig).get(name);copyProperty(dest, name, value);}}} elseif (orig instanceof Map) {@SuppressWarnings("unchecked")final// Map properties are always of type <String, Object>Map<String, Object> propMap = (Map<String, Object>) orig;for (final Map.Entry<String, Object> entry : propMap.entrySet()) {final String name = entry.getKey();if (getPropertyUtils().isWriteable(dest, name)) {copyProperty(dest, name, entry.getValue());}}} else/* if (orig is a standard JavaBean) */ {final PropertyDescriptor[] origDescriptors =getPropertyUtils().getPropertyDescriptors(orig);for (PropertyDescriptor origDescriptor : origDescriptors) {final String name = origDescriptor.getName();if ("class".equals(name)) {continue; // No point in trying to set an object's class}if (getPropertyUtils().isReadable(orig, name) &&getPropertyUtils().isWriteable(dest, name)) {try {final Object value =getPropertyUtils().getSimpleProperty(orig, name);copyProperty(dest, name, value);} catch (final NoSuchMethodException e) {// Should not happen}}}}}

Spring 的 BeanUtils

使用spring的BeanUtils进行对象拷贝:

publicclass TestSpringBeanUtils {public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {//下面只是用于单独测试PersonSource personSource = new PersonSource(1, "pjmike", "12345", 21);PersonDest personDest = new PersonDest();BeanUtils.copyProperties(personSource,personDest);System.out.println("persondest: "+personDest);}
}

Spring下的BeanUtils也是使用 copyProperties方法进行拷贝,只不过它的实现方式非常简单,就是对两个对象中相同名字的属性进行简单的get/set,仅检查属性的可访问性。具体实现如下:

private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,@Nullable String... ignoreProperties) throws BeansException {Assert.notNull(source, "Source must not be null");Assert.notNull(target, "Target must not be null");Class<?> actualEditable = target.getClass();if (editable != null) {if (!editable.isInstance(target)) {throw new IllegalArgumentException("Target class [" + target.getClass().getName() +"] not assignable to Editable class [" + editable.getName() + "]");}actualEditable = editable;}PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);for (PropertyDescriptor targetPd : targetPds) {Method writeMethod = targetPd.getWriteMethod();if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());if (sourcePd != null) {Method readMethod = sourcePd.getReadMethod();if (readMethod != null &&ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {try {if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {readMethod.setAccessible(true);}Object value = readMethod.invoke(source);if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {writeMethod.setAccessible(true);}writeMethod.invoke(target, value);}catch (Throwable ex) {throw new FatalBeanException("Could not copy property '" + targetPd.getName() + "' from source to target", ex);}}}}}}

可以看到,成员变量赋值是基于目标对象的成员列表,并且会跳过ignore的以及在源对象中不存在,所以这个方法是安全的,不会因为两个对象之间的结构差异导致错误,但是必须保证同名的两个成员变量类型相同

小结

以上简要的分析两种BeanUtils,因为Apache下的BeanUtils性能较差,不建议使用,可以使用 Spring的BeanUtils ,或者使用其他拷贝框架,比如:Dozer、ModelMapper等等

来源 | https://urlify.cn/vUfIry

热门内容:选型必看:RabbitMQ 七战 Kafka,差异立现为什么阿里规定需要在事务注解@Transactional中指定rollbackFor?
一套简单通用的Java后台管理系统,拿来即用,非常方便(附项目地址)半吊子架构师,一来就想干掉RabbitMQ ...
前、后端分离权限控制设计和实现思路最近面试BAT,整理一份面试资料《Java面试BAT通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。
明天见(。・ω・。)ノ♡

两难!到底用Apache BeanUtils还是Spring BeanUtils?相关推荐

  1. 对象拷贝 Apache BeanUtils与Spring BeanUtils性能比较

    前言 在我们实际项目开发过程中,我们经常需要将不同的两个对象实例进行属性复制,从而基于源对象的属性信息进行后续操作,而不改变源对象的属性信息,比如DTO数据传输对象和数据对象DO,我们需要将DO对象进 ...

  2. 两难!到底用 Spring BeanUtils 还是 Apache BeanUtils?

    前言 在我们实际项目开发过程中,我们经常需要将不同的两个对象实例进行属性复制,从而基于源对象的属性信息进行后续操作,而不改变源对象的属性信息,比如DTO数据传输对象和数据对象DO,我们需要将DO对象进 ...

  3. 对象拷贝之Apache BeanUtils、Spring的BeanUtils、Mapstruct、BeanCopier、PropertieyUtils对比(深拷贝)

    大多时候时候使用的是Apache或Spring``BeanUtils,今天,我们来看一下一个更高效的属性拷贝方式:BeanCopier. https://github.com/cglib/cglib ...

  4. apache camel_在WildFly中将Apache Camel和Spring添加为jboss模块

    apache camel 这些天,我在玩Wildfly , Apache Camel和Spring . 在EAR / WAR之间进行通信的一种简单方法是使用Camel的direct-vm组件. 有或没 ...

  5. 在WildFly中将Apache Camel和Spring添加为jboss模块

    这些天,我在玩Wildfly , Apache Camel和Spring . 在EAR / WAR之间进行通信的一种简单方法是使用Camel的direct-vm组件. 有或没有骆驼,有很多方法可以实现 ...

  6. 使用Apache cxf 和Spring在Tomcat下发布Webservice指南

    转载 http://blog.csdn.net/zhangzhaokun/article/details/4750021 最近学习了如何使用apache cxf和Spring发布webservice, ...

  7. apache ignite_Kubernetes集群上的Apache Ignite和Spring第1部分:Spring Boot应用程序

    apache ignite 在之前的一系列博客中,我们在Kubernetes集群上启动了一个Ignite集群. 在本教程中,我们将使用先前在Spring Boot Application上创建的Ign ...

  8. Kubernetes集群上的Apache Ignite和Spring第1部分:Spring Boot应用程序

    在之前的一系列博客中,我们在Kubernetes集群上启动了一个Ignite集群. 在本教程中,我们将使用先前在Spring Boot Application上创建的Ignite集群. 让我们使用Sp ...

  9. apache camel_轻量级的开源集成:Apache Camel还是Spring集成?

    apache camel 首先,为全面披露信息,在过去的1.5年中, 我一直担任 FuseSource(现为Red Hat) 的顾问,为零售,运输,银行/金融等不同行业的大型和小型公司提供SOA和集成 ...

最新文章

  1. ACE源代码目录结构
  2. J2ME手游开发日记
  3. 武汉数字工程研究所计算机软件分数,武汉数字工程研究所2017考研成绩查询时间:2月16日...
  4. linux 升级centos7,Linux之从Centos 6.x 升级Centos7
  5. linux路由内核实现分析(一)----邻居子节点(2)
  6. ajax跨越html,ajax跨域的解决方案
  7. 利用zabbix监控mysqldump定时备份数据库是否成功 乐维君
  8. unity零基础学习
  9. SQL Server2005彻底卸载
  10. Flex builder3 调试弹出窗口Flex builder cannot locate the required version of Flash Player解决办法
  11. 「干货分享」我所在团队的竞品分析模板--附下载
  12. 2021 年“泰迪杯”数据分析技能赛 B 题 肥料登记数据分析
  13. HDOJ 1025 DP
  14. UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xfe in position 198369: illegal multibyte sequenc
  15. python-普通pdf的添加水印
  16. 【Try to Hack】veil-evasion免杀
  17. 5.node.js中的事件循环
  18. C++项目实战-先把项目跑起来看看
  19. mysql字符串分割为数组_mysql下将分隔字符串转换为数组
  20. 百度文库如何申请个人认证?需要什么资质?

热门文章

  1. DRF (Django REST framework) 中的视图类
  2. Firetruck UVA - 208
  3. jQuery中getJSON跨域原理详解
  4. 根据二叉树的前序遍历和中序遍历重建二叉树
  5. Android 4.2真坑爹
  6. C#进行Visio二次开发之电气线路停电分析逻辑
  7. 四月青少年编程组队学习(Python一级)Task02
  8. LSGO软件技术团队招新
  9. 六一:如何在Datawhale开源学习小程序中管
  10. 如何利用Gephi可视化浏览的网站关系