How do I copy an object in Java?

后端 未结 23 2607
终归单人心
终归单人心 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:30

    public class MyClass implements Cloneable {
    
    private boolean myField= false;
    // and other fields or objects
    
    public MyClass (){}
    
    @Override
    public MyClass clone() throws CloneNotSupportedException {
       try
       {
           MyClass clonedMyClass = (MyClass)super.clone();
           // if you have custom object, then you need create a new one in here
           return clonedMyClass ;
       } catch (CloneNotSupportedException e) {
           e.printStackTrace();
           return new MyClass();
       }
    
      }
    }
    

    and in your code:

    MyClass myClass = new MyClass();
    // do some work with this object
    MyClass clonedMyClass = myClass.clone();
    

提交回复
热议问题