BeanUtils.copyProperties的用法

参考一

what?

BeanUtils它提供了对java反射和自省API的包装。它里面还有很多工具类,这里我们介绍一下copyProperties。

why? 

我们如果有两个具有很多相同属性的JavaBean,一个很常见的情况就是Struts里的PO对象(持久对象)和对应的ActionForm,传统的方式对属性逐个赋值:

如果按照上面那种赋值方式,是非常麻烦的,而且代码梁可以估计会很多

How?

这时候我们如果用copyProperties,直接一行代码,然后就搞定了。

例如:

 

 

 

但是有几点我们需要注意:

BeanUtils.copyProperties(a, b);

b中的存在的属性,a中一定要有,但是a中可以有多余的属性;
a中与b中相同的属性都会被替换,不管是否有值;
a、 b中的属性要名字相同,才能被赋值,不然的话需要手动赋值;
Spring的BeanUtils的CopyProperties方法需要对应的属性有getter和setter方法;
如果存在属性完全相同的内部类,但是不是同一个内部类,即分别属于各自的内部类,则spring会认为属性不同,不会copy;
spring和apache的copy属性的方法源和目的参数的位置正好相反,所以导包和调用的时候都要注意一下。

参考二:

1、简介

BeanUtils提供对Java反射和自省API的包装。其主要目的是利用反射机制对JavaBean的属性进行处理。

2、用法

 

如果有两个具有很多相同属性的JavaBean,一个很常见的情况就是Struts里的PO对象(持久对象)和对应的ActionForm。例如:一个用户注册页面,有一个User实体类和一个UserActionForm实体类,我们一般会在Action里从ActionForm构造一个PO对象,传统的方式是使用类似下面的语句对属性逐个赋值:

复制代码
// 获取 ActionForm 表单数据 
 UserActionForm uForm = (UserActionForm) form; 
 
// 构造一个User对象 
User user = new User(); 
  
// 逐一赋值 
user.setUsername(uForm.getUsername); 
user.setPassword(uForm.getPassword); 
user.setAge(uForm.getAge); 
........... 
........... 
  
// 然后调用JDBC、或操作Hibernate 持久化对象User到数据库 
...
复制代码

通过这样的方法如果表单属性字段很多,达到了100、1000甚至更多,那我们不是要写100、1000行set、get了。谁都不愿意这样做。

而我们使用 BeanUtils.copyProperties() 方法以后,代码量大大的减少,而且整体程序看着也简洁明朗,代码如下:

复制代码
// 获取 ActionForm 表单数据 
UserActionForm uForm = (UserActionForm) form; 
 
// 构造一个User对象 
User user = new User(); 
  
// 赋值 
BeanUtils.copyProperties(user, uForm); 
 
// 然后调用JDBC、或操作Hibernate 持久化对象User到数据库 
.......
复制代码

注:如果User和UserActionForm 间存在名称不相同的属性,则BeanUtils不对这些属性进行处理,需要手动处理。例如:
User类里面有个createDate 创建时间字段,而UserActionForm里面无此字段。BeanUtils.copyProperties()不会对此字段做任何处理。必须要自己手动处理。
用法总结如下:

[java] view plain copy print?
 
BeanUtils.copyProperties("要转换的类", "转换后的类"); 
[java] view plain copy print?
 
PropertyUtils.copyProperties("要转换的类", "转换后的类");

用法其实很简单,第一个参数是要转换的类,第二个参数是转换后的类。

BeanUtils.copyProperties VS PropertyUtils.copyProperties

两者最大的区别是:

BeanUtils.copyProperties会进行类型转换,而PropertyUtils.copyProperties不会。
既然进行了类型转换,那BeanUtils.copyProperties的速度比不上PropertyUtils.copyProperties。

因此,PropertyUtils.copyProperties应用的范围稍为窄一点,它只对名字和类型都一样的属性进行copy,如果名字一样但类型不一样,它会报错。

使用BeanUtils有几个要注意的地方:

1.对于类型为Boolean/Short/Integer/Float/Double的属性,它会转换为0:

复制代码
public class User { 
  
 private Integer intVal; 
   
 private Double doubleVal; 
   
 private Short shortVal; 
   
 private Long longVal; 
   
 private Float floatVal; 
   
 private Byte byteVal; 
   
 private Boolean booleanVal; 
} 
  
User src = new User(); 
User dest = new User(); 
BeanUtils.copyProperties(dest, src); 
System.out.println(src); 
System.out.println(dest); 
  
//输出  
User [intVal=null, doubleVal=null, shortVal=null, longVal=null, floatVal=null, byteVal=null, booleanVal=null] 
User [intVal=0, doubleVal=0.0, shortVal=0, longVal=0, floatVal=0.0, byteVal=0, booleanVal=false]
复制代码

在stackoverflow上有人解释说是因为这几个类型都有对应的基本类型,在进行类型转换时,有可能遇到类似Integer -> int的转换,此时显然不能对int类型的属性赋值为null,因此统一转换为0。

如何让它不要转为0呢?可以这样:

import org.apache.commons.beanutils.converters.IntegerConverter; 
  
IntegerConverter converter = new IntegerConverter(null); //默认为null,而不是0 
BeanUtilsBean beanUtilsBean = new BeanUtilsBean(); 
beanUtilsBean.getConvertUtils().register(converter, Integer.class); 

2.对于java.util.Date/BigDecimal/java.sql.Date/java.sql.Timestamp/java.sql.Time这几个类,如果值为null,则在copy时会抛异常,需要使用对应的Conveter:

复制代码
public class User2 { 
  
 private java.util.Date javaUtilDateVal; 
   
 private java.sql.Date javaSqlDateVal; 
   
 private java.sql.Timestamp javaSqlTimeStampVal; 
   
 private BigDecimal bigDecimalVal; 
  
 private java.sql.Time javaSqlTime; 
  
} 
  
User2 src = new User2(); 
User2 dest = new User2(); 
  
BeanUtilsBean beanUtilsBean = new BeanUtilsBean(); 
  
//如果没有下面几行,则在转换null时会抛异常,例如:org.apache.commons.beanutils.ConversionException: No value specified for 'BigDecimal' 
//在org.apache.commons.beanutils.converters这个包下面有很多的Converter,可以按需要使用 
beanUtilsBean.getConvertUtils().register(new org.apache.commons.beanutils.converters.BigDecimalConverter(null), BigDecimal.class); 
beanUtilsBean.getConvertUtils().register(new org.apache.commons.beanutils.converters.DateConverter(null), java.util.Date.class); 
  
beanUtilsBean.getConvertUtils().register(new org.apache.commons.beanutils.converters.SqlTimestampConverter(null), java.sql.Timestamp.class); 
beanUtilsBean.getConvertUtils().register(new org.apache.commons.beanutils.converters.SqlDateConverter(null), java.sql.Date.class); 
beanUtilsBean.getConvertUtils().register(new org.apache.commons.beanutils.converters.SqlTimeConverter(null), java.sql.Time.class); 
  
beanUtilsBean.copyProperties(dest, src); 
System.out.println(src); 
System.out.println(dest);
复制代码

使用BeanUtils还会经常碰到这样变态的需求:

假设是从A复制到B:
需求1:如果B中某字段有值(不为null),则该字段不复制;也就是B中该字段没值时,才进行复制,适合于对B进行补充值的情况。
需求2:如果A中某字段没值(为null),则该字段不复制,也就是不要把null复制到B当中。

对于需求1,可以这样:

复制代码
import org.apache.commons.beanutils.BeanUtilsBean; 
import org.apache.commons.beanutils.PropertyUtils; 
  
public class CopyWhenNullBeanUtilsBean extends BeanUtilsBean{ 
  
 @Override
 public void copyProperty(Object bean, String name, Object value) 
   throws IllegalAccessException, InvocationTargetException { 
  try { 
   Object destValue = PropertyUtils.getSimpleProperty(bean, name); 
   if (destValue == null) { 
    super.copyProperty(bean, name, value); 
   } 
  } catch (NoSuchMethodException e) { 
   throw new RuntimeException(e); 
  } 
 } 
  
}
复制代码

对于需求2,可以这样:

复制代码
import org.apache.commons.beanutils.BeanUtilsBean; 
  
public class CopyFromNotNullBeanUtilsBean extends BeanUtilsBean { 
  
 @Override
 public void copyProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { 
  if (value == null) { 
   return; 
  } 
  super.copyProperty(bean, name, value); 
 } 
}
复制代码

 

 

 

 

 

参考:

https://blog.csdn.net/dfshsdr/article/details/90513676

https://www.jb51.net/article/186524.htm

import org.apache.commons.beanutils.BeanUtilsBean;
  
public class CopyFromNotNullBeanUtilsBean extends BeanUtilsBean {
  
 @Override
 public void copyProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException {
  if (value == null) {
   return;
  }
  super.copyProperty(bean, name, value);
 }
}
posted @   哩个啷个波  阅读(2032)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示