org.springframework.beans.Beanutils copyProperties 原理

来源:互联网 发布:程序员离职交接文档 编辑:程序博客网 时间:2024/05/21 21:02

org.springframework.beans.Beanutils copyProperties 原理

BeanUtils. copyProperties(source,targe)原理:

  1. 根据source的属性来向target同名属性设值。 
    • 若target无该属性,则不设
    • 名字相同,基本类型和封装类型可以完成映射
    • 若target有source无,则target属性值为null(基本类型则为初始值,如int 为 0)
  2. 调用原理 target.set + source的属性名(source.get + source的属性名):所有source必须有get方法,target必须有set方法

下面是例子

import org.springframework.beans.BeanUtils;

public class BeanUtilsTest {
    public static void main(String[] args) {
        Source source = new Source() {{
            setId(1111111);
        }};

        Target target = new Target();
        BeanUtils.copyProperties(source,target);
        System.out.println(source);
        System.out.println(target);

    }
}


class Source {
    int id;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    @Override
    public String toString() {
        return "Cat{" +
                "id=" + id +
                '}';
    }
}

class Target {
    // id换名 则无法赋值
    Integer id;
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "id=" + id +
                '}';
    }
}
0 1
原创粉丝点击