How do I copy an object in Java?

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

    Create a copy constructor:

    class DummyBean {
      private String dummy;
    
      public DummyBean(DummyBean another) {
        this.dummy = another.dummy; // you can access  
      }
    }
    

    Every object has also a clone method which can be used to copy the object, but don't use it. It's way too easy to create a class and do improper clone method. If you are going to do that, read at least what Joshua Bloch has to say about it in Effective Java.

提交回复
热议问题