How do I copy an object in Java?

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

    You can deep copy automatically with XStream, from http://x-stream.github.io/:

    XStream is a simple library to serialize objects to XML and back again.

    Add it to your project (if using maven)

    
        com.thoughtworks.xstream
        xstream
        1.3.1                
    
    

    Then

    DummyBean dum = new DummyBean();
    dum.setDummy("foo");
    DummyBean dumCopy = (DummyBean) XSTREAM.fromXML(XSTREAM.toXML(dum));
    

    With this you have a copy without the need to implement any cloning interface.

提交回复
热议问题