How do I copy an object in Java?

后端 未结 23 2676
终归单人心
终归单人心 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条回答
  •  梦毁少年i
    2020-11-21 05:25

    Alternative to egaga's constructor method of copy. You probably already have a POJO, so just add another method copy() which returns a copy of the initialized object.

    class DummyBean {
        private String dummyStr;
        private int dummyInt;
    
        public DummyBean(String dummyStr, int dummyInt) {
            this.dummyStr = dummyStr;
            this.dummyInt = dummyInt;
        }
    
        public DummyBean copy() {
            return new DummyBean(dummyStr, dummyInt);
        }
    
        //... Getters & Setters
    }
    

    If you already have a DummyBean and want a copy:

    DummyBean bean1 = new DummyBean("peet", 2);
    DummyBean bean2 = bean1.copy(); // <-- Create copy of bean1 
    
    System.out.println("bean1: " + bean1.getDummyStr() + " " + bean1.getDummyInt());
    System.out.println("bean2: " + bean2.getDummyStr() + " " + bean2.getDummyInt());
    
    //Change bean1
    bean1.setDummyStr("koos");
    bean1.setDummyInt(88);
    
    System.out.println("bean1: " + bean1.getDummyStr() + " " + bean1.getDummyInt());
    System.out.println("bean2: " + bean2.getDummyStr() + " " + bean2.getDummyInt());
    

    Output:

    bean1: peet 2
    bean2: peet 2
    
    bean1: koos 88
    bean2: peet 2
    

    But both works well, it is ultimately up to you...

提交回复
热议问题