spring 对象复制工具类 BeanUtils.copyProperties
原创    java_world    发表于:2018-01-03 11:03:38
  阅读 :54   收藏   编辑

概述

Spring提供了一个非常简便的对象复制方法,常用如下:

BeanUtils.copyProperties(source, target);
BeanUtils.copyProperties(source, target, ignoreProperties);

实例

创建一个bean

import java.io.Serializable;

public class Girl implements Serializable {

    private Integer age;
    private String name;
    private String phone;

    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Girl [age=" + age + ", name=" + name + ", phone=" + phone + "]";
    }
}

测试类

public class Test {


    public static void main(String[] args) {


        Girl girl = new Girl();
        girl.setAge(18);
        girl.setName("Marley");
        girl.setPhone("110");

        Girl firstGirl = new Girl();

        /**
         * source 源bean
         * target 目标bean
         */
        BeanUtils.copyProperties(girl, firstGirl);


        System.err.println(firstGirl);

        //输出结果:Girl [age=18, name=Marley, phone=110]

        Girl secondGirl = new Girl();


        /**
         * source 源bean
         * target 目标bean
         * ignoreProperties 忽略的属性
         */
        String[] ignoreProperties = {"age"};
        BeanUtils.copyProperties(girl, secondGirl,ignoreProperties);


        System.err.println(secondGirl);

        //输出结果:Girl [age=null, name=Marley, phone=110]
    }
}
评论
条评论

推荐阅读