How do I copy an object in Java?

后端 未结 23 2666
终归单人心
终归单人心 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:32
    class DB {
      private String dummy;
    
      public DB(DB one) {
        this.dummy = one.dummy; 
      }
    }
    
    0 讨论(0)
  • 2020-11-21 05:34

    You can try to implement Cloneable and use the clone() method; however, if you use the clone method you should - by standard - ALWAYS override Object's public Object clone() method.

    0 讨论(0)
  • 2020-11-21 05:35

    Yes. You need to Deep Copy your object.

    0 讨论(0)
  • 2020-11-21 05:35

    To do that you have to clone the object in some way. Although Java has a cloning mechanism, don't use it if you don't have to. Create a copy method that does the copy work for you, and then do:

    dumtwo = dum.copy();
    

    Here is some more advice on different techniques for accomplishing a copy.

    0 讨论(0)
  • 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();

    0 讨论(0)
提交回复
热议问题