简体   繁体   English

链式Java Deep Copy?

[英]Chained Java Deep Copy?

I understand how to do a java deep copy using Serializable and Streams but as long as the object to copy has only primitive data types. 我理解如何使用Serializable和Streams进行java深度复制,但只要要复制的对象只有原始数据类型。 In my case I have a parent class that contains among primitive data types an ArrayList of a child class, and they also need to be deep copied. 在我的例子中,我有一个父类,它包含原始数据类型和子类的ArrayList,并且它们也需要进行深度复制。

Can someone please point me to the right direction to do it? 有人可以指出我正确的方向吗?

UPDATE: 更新:

I thought it was working but I just realize it is not. 我认为它有效但我只是意识到它不是。

This is what I have. 这就是我所拥有的。

public class Pack implements Serializable
      {
      String ID;
      String serviceCode;
      String name;
      String type;
      ArrayList<Service> services;
      public Pack deepClone()
      {
        try 
            {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);

            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            Pack clone = (Pack) ois.readObject();
            clone.setID(null);
            clone.setType("Replica");
            return clone;
            } 
            catch (IOException e) 
                {
                return null;
                }
            catch (ClassNotFoundException e) 
                {
                    return null;
                }
        }
      }


public class Service implements Serializable
     {
     String ID;
     String serviceCode;
     String name;
     }

Now after cloning a Parent class a get a nice clone but the services array is null. 现在克隆一个Parent类后得到一个很好的克隆,但services数组为null。

UPDATE: 更新:

Sorry my mistake, it was the lack of sleep. 对不起我的错误,那就是睡眠不足。 It is indeed working. 它确实有效。

Serialization is done no matter either you have primitive data types or not. 无论您是否具有原始数据类型,都会进行序列化。 The only condition is that your child classes need to be serializable too. 唯一的条件是您的子类也需要可序列化。

Refer here for a quick tutorial java_serialization 请参阅此处以获取快速教程java_serialization

只需要确保该数组列表的对象也实现了可序列化,即您的子类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM