How do I copy an object in Java?

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

提交回复
热议问题