BeanUtils.copyProperties 和 PropertyUtils.copyProperties 

两个工具类都是对两个bean之前存在name相同的属性进行处理,无论是源bean或者目标bean多出的属性均不处理。

其原理是通过JDK自带的反射机制动态的去get,set,从而去转换我们的类。

但是要注意一点他们所支持的数据类型,还有一个就是假如一个类里面又写了一个类,一般叫做内部类,像这种类进行转换的时候,是不会成功的。

两者最大的区别是: 
1.BeanUtils.copyProperties会进行类型转换,而PropertyUtils.copyProperties不会。 
既然进行了类型转换,那BeanUtils.copyProperties的速度比不上PropertyUtils.copyProperties。 
因此,PropertyUtils.copyProperties应用的范围稍为窄一点,它只对名字和类型都一样的属性进行copy,如果名字一样但类型不一样,它会报错。

 2.对null的处理:PropertyUtils支持为null的场景;BeanUtils对部分属性不支持null的情况,具体为下:

Boolean、Ineger、Long、Short、Float、Double等不支持: 转为false、0;
3)、string:支持,保持null;

使用BeanUtils有几个要注意的地方: 
1.对于类型为Boolean/Short/Integer/Float/Double的属性,它会转换为false、0: 

 1 public class User {  
 2   
 3     private Integer intVal;  
 4       
 5     private Double doubleVal;  
 6       
 7     private Short shortVal;  
 8       
 9     private Long longVal;  
10       
11     private Float floatVal;  
12       
13     private Byte byteVal;  
14       
15     private Boolean booleanVal;  
16 }  
17   
18 User src = new User();  
19 User dest = new User();  
20 BeanUtils.copyProperties(dest, src);  
21 System.out.println(src);  
22 System.out.println(dest);  
23   
24 //输出结果:      
25 User [intVal=null, doubleVal=null, shortVal=null, longVal=null, floatVal=null, byteVal=null, booleanVal=null]  
26 User [intVal=0, doubleVal=0.0, shortVal=0, longVal=0, floatVal=0.0, byteVal=0, booleanVal=false]  
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-01
  • 2021-11-10
  • 2021-10-11
  • 2022-12-23
  • 2021-09-25
猜你喜欢
  • 2021-08-05
  • 2021-12-13
  • 2022-12-23
  • 2021-10-12
  • 2022-12-23
相关资源
相似解决方案