Spring BeanUtils.copyProperties不起作用

时间:2017-01-09 23:42:17

标签: spring

我想将属性从一个对象复制到另一个对象,两者都属于同一个类。然而,它不是复制字段。这是演示代码:

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 +
            '}';
    }
}

输出是:

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}

1 个答案:

答案 0 :(得分:2)

看起来我必须为该课程设置setter / getters:

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 +
            '}';
    }
}

现在输出是:

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}