How do I copy an object in Java?

后端 未结 23 3140
终归单人心
终归单人心 2020-11-21 04:50

Consider the code below:

DummyBean dum = new DummyBean();
dum.setDummy(\"foo\");
System.out.println(dum.getDummy()); // prints \'foo\'

DummyBean dumtwo = du         


        
23条回答
  •  無奈伤痛
    2020-11-21 05:36

    Deep Cloning is your answer, which requires implementing the Cloneable interface and overriding the clone() method.

    public class DummyBean implements Cloneable {
    
       private String dummy;
    
       public void setDummy(String dummy) {
          this.dummy = dummy;
       }
    
       public String getDummy() {
          return dummy;
       }
    
       @Override
       public Object clone() throws CloneNotSupportedException {
          DummyBean cloned = (DummyBean)super.clone();
          cloned.setDummy(cloned.getDummy());
          // the above is applicable in case of primitive member types like String 
          // however, in case of non primitive types
          // cloned.setNonPrimitiveType(cloned.getNonPrimitiveType().clone());
          return cloned;
       }
    }
    

    You will call it like this DummyBean dumtwo = dum.clone();

提交回复
热议问题