How do I copy an object in Java?

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

    Pass the object that you want to copy and get the object you want:

    private Object copyObject(Object objSource) {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos);
                oos.writeObject(objSource);
                oos.flush();
                oos.close();
                bos.close();
                byte[] byteData = bos.toByteArray();
                ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
                try {
                    objDest = new ObjectInputStream(bais).readObject();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return objDest;
    
        }
    

    Now parse the objDest to desired object.

    Happy Coding!

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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...

    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-11-21 05:30
    public class MyClass implements Cloneable {
    
    private boolean myField= false;
    // and other fields or objects
    
    public MyClass (){}
    
    @Override
    public MyClass clone() throws CloneNotSupportedException {
       try
       {
           MyClass clonedMyClass = (MyClass)super.clone();
           // if you have custom object, then you need create a new one in here
           return clonedMyClass ;
       } catch (CloneNotSupportedException e) {
           e.printStackTrace();
           return new MyClass();
       }
    
      }
    }
    

    and in your code:

    MyClass myClass = new MyClass();
    // do some work with this object
    MyClass clonedMyClass = myClass.clone();
    
    0 讨论(0)
  • 2020-11-21 05:32

    Other than explicitly copying, another approach is to make the object immutable (no set or other mutator methods). In this way the question never arises. Immutability becomes more difficult with larger objects, but that other side of that is that it pushes you in the direction of splitting into coherent small objects and composites.

    0 讨论(0)
提交回复
热议问题