How do I copy an object in Java?

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

    Just follow as below:

    public class Deletable implements Cloneable{
    
        private String str;
        public Deletable(){
        }
        public void setStr(String str){
            this.str = str;
        }
        public void display(){
            System.out.println("The String is "+str);
        }
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
    

    and wherever you want to get another object, simple perform cloning. e.g:

    Deletable del = new Deletable();
    Deletable delTemp = (Deletable ) del.clone(); // this line will return you an independent
                                     // object, the changes made to this object will
                                     // not be reflected to other object
    

提交回复
热议问题