BeanUtils.copyProperties方法

BeanUtils.copyProperties会进行类型转换;

BeanUtils.copyProperties方法简单来说就是将两个字段相同的对象进行属性值的复制。如果两个对象之间存在名称不相同的属性,则 BeanUtils 不对这些属性进行处理,需要程序手动处理。

这两个类在不同的包下面,而这两个类的copyProperties()方法里面传递的参数赋值是相反的

"转换后的类"中的存在的属性,"转换前的类"中一定要有,但是"转换前的类"中可以有多余的属性;

"转换前的类"中与"转换后的类"中相同的属性都会被替换,不管是否有值;

"转换前的类"、 "转换后的类"中的属性要名字相同,才能被赋值,不然的话需要手动赋值;

一、 org.springframework.beans.BeanUtils

a拷贝到b(a,b为对象)

BeanUtils.copyProperties(a,b);

二、org.apache.commons.beanutils.BeanUtils

b拷贝到a(a,b为对象)

BeanUtils.copyProperties(a,b);

三、示例代码(org.apache.commons.beanutils.BeanUtils)

1、导入的maven依赖包

        
        
            commons-beanutils
            commons-beanutils
            1.9.4
        

2、示例代码

a、实体类1

@Data
public class Test1 {
        private String name;
        private Integer age;
        private Integer stature;
}

b、实体类2

@Data
public class Test2 {
    private String name;
    private String age;
    private Integer stature;
}

c、main所在类

import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;

public class Demo {
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        Test1 test1 = new Test1();
        Test2 test2 = new Test2();
        test1.setName("An");
        test1.setAge(30);
        test1.setStature(180);
        System.out.println(test1);
        System.out.println(test2);
        BeanUtils.copyProperties(test2, test1);
        System.out.println(test1);
        System.out.println(test2);
    }
}

3、运行结果:

将test1的值赋给test2

BeanUtils.copyProperties方法_第1张图片

你可能感兴趣的:(JAVA知识点杂烩,java,开发语言)