Java对象复制或拷贝之BeanUtils.copyProperties() 用法,一行语句实现对象间快速复制

x33g5p2x  于2022-07-20 转载在 Java  
字(1.0k)|赞(0)|评价(0)|浏览(470)

java对象复制或拷贝之BeanUtils.copyProperties() 用法,一行语句实现对象间快速复制


BeanUtils.copyProperties(源对象, 目标对象);

使用注意事项:

1.BeanUtils是org.springframework.beans.BeanUtils,不是org.apache.commons.beanutils.BeanUtils

2.必须有get、set方法

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private String name;

    private String gender;

    private Integer age;

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                '}';
    }
}

测试代码如下:

package com.example.test;

import org.springframework.beans.BeanUtils;

public class TestUser {

    public static void main(String[] args) {
        User u1 = new User("aa", "男", 20);
        System.out.println(u1.hashCode());
        System.out.println(u1);
        System.out.println("------------");
        User target = new User();
        BeanUtils.copyProperties(u1,target);
        System.out.println(target.hashCode());
        target.setAge(22); //进行修改
        System.out.println(target);
    }
}

结果:

2016447921
User{name='aa', gender='男', age=20}
------------
20671747
User{name='aa', gender='男', age=22}

相关文章