How do I copy an object in Java?

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

    If you can add an annotation to the source file, an annotation processor or code generator like this one can be used.

    import net.zerobuilder.BeanBuilder
    
    @BeanBuilder
    public class DummyBean { 
      // bean stuff
    }
    

    A class DummyBeanBuilders will be generates, which has a static method dummyBeanUpdater to create shallow copies, the same way as you would do it manually.

    DummyBean bean = new DummyBean();
    // Call some setters ...
    // Now make a copy
    DummyBean copy = DummyBeanBuilders.dummyBeanUpdater(bean).done();
    

提交回复
热议问题