差不多相同属性的类的值的复制

main方法

BeanUtils的包路径

import org.springframework.beans.BeanUtils;

实验逻辑:
A,B两个类有相同和不相同的属性,
现在想把A中属性的值复制到B类中。

public static void main(String[] args) {

        A aDto = new A();
        B bDto = new B();

        aDto.setA("a");
        aDto.setB("b");
        aDto.setC("c");
        aDto.setD("d");

        BeanUtils.copyProperties(aDto, bDto);
        System.out.println(aDto.toString());
        System.out.println(bDto.toString());
        bDto.setE("e");
        bDto.setF("f");
        bDto.setI(1);
        System.out.println(bDto.toString());

    }
执行打印出来的结果:
A{a='a', b='b', c='c', d='d'}
B{a='a', c='c', d='d', e='null', f='null', i=0}
B{a='a', c='c', d='d', e='e', f='f', i=1}

A类

class A implements Serializable {
    private static final long serialVersionUID = 1L;

    private String a;
    private String b;
    private String c;
    private String d;


    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }

    public String getB() {
        return b;
    }

    public void setB(String b) {
        this.b = b;
    }

    public String getC() {
        return c;
    }

    public void setC(String c) {
        this.c = c;
    }

    public String getD() {
        return d;
    }

    public void setD(String d) {
        this.d = d;
    }

    @Override
    public String toString() {
        return "A{" +
                "a='" + a + '\'' +
                ", b='" + b + '\'' +
                ", c='" + c + '\'' +
                ", d='" + d + '\'' +
                '}';
    }
}

B类

class B implements Serializable {
    private static final long serialVersionUID = 1L;
    private String a;
    private String c;
    private String d;
    private String e;
    private String f;
    private int i;

    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }


    public String getC() {
        return c;
    }

    public void setC(String c) {
        this.c = c;
    }

    public String getD() {
        return d;
    }

    public void setD(String d) {
        this.d = d;
    }

    public String getE() {
        return e;
    }

    public void setE(String e) {
        this.e = e;
    }

    public String getF() {
        return f;
    }

    public void setF(String f) {
        this.f = f;
    }

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }

    @Override
    public String toString() {
        return "B{" +
                "a='" + a + '\'' +
                ", c='" + c + '\'' +
                ", d='" + d + '\'' +
                ", e='" + e + '\'' +
                ", f='" + f + '\'' +
                ", i=" + i +
                '}';
    }

你可能感兴趣的:(java基础,java类属性值复制)