2011-02-01 48 views

回答

1

在下議院的BeanUtils copyProperties(...)可能是你想要通過在兩個不同的豆類匹配的getter/setter什麼。

public class Test 
{ 

    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException 
    { 
     new Test().run(); 
    } 

    private void run() throws IllegalAccessException, InvocationTargetException 
    { 
     Bean1 one = new Bean1(); 
     one.setProp1("Foo"); 

     Bean2 two = new Bean2(); 

     BeanUtils.copyProperties(two, one); 

     System.out.println(ToStringBuilder.reflectionToString(one)); 
     System.out.println(ToStringBuilder.reflectionToString(two)); 
    } 

    public class Bean1 
    { 
     private String propbean1; 

     public String getProp1() 
     { 
      System.out.println("bean1 getter"); 
      return propbean1; 
     } 

     public void setProp1(String s) 
     { 
      System.out.println("bean1 setter"); 
      propbean1 = s; 
     } 
    } 

    public class Bean2 
    { 
     private String propbean2; 

     public String getProp1() 
     { 
      System.out.println("bean2 getter"); 
      return propbean2; 
     } 

     public void setProp1(String s) 
     { 
      System.out.println("bean2 setter"); 
      propbean2 = s; 
     } 
    } 
} 

打印

bean1 setter 
bean1 getter 
bean2 setter 
[email protected][propbean1=Foo] 
[email protected][propbean2=Foo] 
1
  1. Java提供的clone()進行淺拷貝,但可以擴展到執行深層副本。 Read here瞭解更多詳情。
  2. Object Serialization technique can be used for the same.
+0

我2個Java對象可以是不同類型的,但我感興趣的只是複製他們的屬性。 – 2011-02-01 04:12:39

+0

+1用於添加序列化作爲選項。這也是一個有多方面的好處,除非你生活在真空中。 – 2011-02-01 05:17:15