父类和子类同时存在相同属性BeanUtils的copyProperties复制

一、几种属性拷贝方法比较

1.几种拷贝方法对比

①org.apache.commons.beanutils.BeanUtils;
②org.apache.commons.beanutils.PropertyUtils;
③org.springframework.beans.BeanUtils
对比1: PropertyUtils的copyProperties()方法几乎与BeanUtils.copyProperties()相同,主要的区别在于后者提供类型转换功能,即发现两个JavaBean的同名属性为不同类型时,在支持的数据类型范围内进行转换,PropertyUtils不支持这个功能,所以说BeanUtils速度会更快一些,使用更普遍一点,犯错的风险更低一点。

2.关于BeanUtils

1)Spring 中的BeanUtils与apache中的BeanUtils区别

org.apache.commons.beanutils.BeanUtils#copyProperties方法会进行类型转换,默认情况下会将Ineger、Boolean、Long等基本类型包装类为null时的值复制后转换成0或者false,有时这个可能会引起不必要的麻烦。
而org.springframework.beans.BeanUtils.copyProperties(bookDto, book);则不会!
关于import org.apache.commons.beanutils.BeanUtils的一些该注意的地方:
BeanUtils支持的转换类型如下:

	BigDecimal					BigInteger
	boolean and Boolean			byte and Byte	
	char and Character			Class
	double and Double			float and Float
	int and Integer				long and Long
	short and Short				String
	java.sql.Date				java.sql.Time
	java.sql.Timestamp

这里要注意一点,java.util.Date是不被支持的,而它的子类java.sql.Date是被支持的。因此如果对象包含时间类型的属性,且希望被转换的时候,一定要使用java.sql.Date类型。否则在转换时会提示argument mistype异常。


来自 langqiao123 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/langqiao123/article/details/72961332?utm_source=copy

2)性能测试

原来公司里面有个技术大牛对org.apache.commons.beanutils.BeanUtils和org.springframework.beans.BeanUtils拷贝性能进行测试,spring 包BeanUtils的性能更佳。

二、.BeanUtils父类和子类同时存在相同名称属性的拷贝

1.问题

父类存在一个属性,子类extends父类又写了相同的属性,在对象属性拷贝后,属性的值存放在哪。

2.实验

1)代码准备

父类

package bean;
import lombok.Data;
@Data
public class Parent {

    private String name;
    
    private String age;
}

子类

@Data
public class Son extends Parent {
    //属性名与父类相同
    private String name;
    private Integer soz;

}

copy source类

package bean;

import lombok.Data;

@Data
public class Person {
    //属性名相同,类型相同
    private String name;
    //属性名相同,类型不同
    private Long age;

    private Integer soz;
}

测试类

package bean;


public class CopyTest {

    public static void main(String[] args) throws Exception{
        Person person = new Person();
        person.setName("person");
        person.setAge(1L);
        person.setSoz(0);

        //子类
        Son son = new Son();
        //copy
        org.springframework.beans.BeanUtils.copyProperties(person,son);
        org.apache.commons.beanutils.BeanUtils.copyProperties(son,person);
    }
}

在这里插入图片描述

拷贝后,son.name有值,parent.name为空。
通过查阅BeanUtils.copyProperties方法源码,发现属性是通过反射调用setter设置属性值,而子类与父类的setName方法同名,相当于子类覆盖了父类的方法,所以拷贝之后属性的值存在于子类的属性中。
这一点,可以在子类中加上下面方法验证

 public void setName(String name) {
        super.setName(name);
        this.name = name;
    }

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u012786993/article/details/82923064
今日推荐