Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring BeanUtils.copyProperties not working

Tags:

spring

I want to copy properties from one object to another, both are of the same class. However it's not copying the fields. Here is the demo code:

public static void main(String[] args) throws Exception {
    A from = new A();
    A to = new A();
    from.i = 123;
    from.l = 321L;
    System.out.println(from.toString());
    System.out.println(to.toString());
    BeanUtils.copyProperties(from, to);
    System.out.println(from.toString());
    System.out.println(to.toString());
}

public static class A {
    public String s;
    public Integer i;
    public Long l;

    @Override
    public String toString() {
        return "A{" +
            "s=" + s +
            ", i=" + i +
            ", l=" + l +
            '}';
    }
}

And the output is:

A{s=null, i=123, l=321}
A{s=null, i=null, l=null}
A{s=null, i=123, l=321}
A{s=null, i=null, l=null}
like image 910
WoLfPwNeR Avatar asked Jun 16 '26 10:06

WoLfPwNeR


1 Answers

Looks like I have to have setter/getters for the class:

public static void main(String[] args) throws Exception {
    A from = new A();
    A to = new A();
    from.i = 123;
    from.l = 321L;
    System.out.println(from.toString());
    System.out.println(to.toString());
    BeanUtils.copyProperties(from, to);
    System.out.println(from.toString());
    System.out.println(to.toString());
}

public static class A {
    public String s;
    public Integer i;
    public Long l;

    public String getS() {
        return s;
    }

    public void setS(String s) {
        this.s = s;
    }

    public Integer getI() {
        return i;
    }

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

    public Long getL() {
        return l;
    }

    public void setL(Long l) {
        this.l = l;
    }

    @Override
    public String toString() {
        return "A{" +
            "s=" + s +
            ", i=" + i +
            ", l=" + l +
            '}';
    }
}

Now the output is:

A{s=null, i=123, l=321}
A{s=null, i=null, l=null}
A{s=null, i=123, l=321}
A{s=null, i=123, l=321}
like image 174
WoLfPwNeR Avatar answered Jun 19 '26 04:06

WoLfPwNeR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!