2017-01-09 83 views
0

あるオブジェクトから別のオブジェクトにプロパティをコピーしたいのですが、どちらも同じクラスです。しかし、それはフィールドをコピーしていません。Spring BeanUtils.copyPropertiesが機能しない

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

はルックス:

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} 
関連する問題