Java Object Deep Copy

1 用序列化进行深度拷贝

  1. Ensure that all classes in the object's graph are serializable
  2. Create input and output streams.
  3. Use the input and output streams to create object input and object output streams.
  4. Pass the object that you want to copy to the object output stream.
  5. Read the new object from the object input stream and cast it back to the class of the object you sent.
public static Object deepClone(Object object) {
    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(baos);
      oos.writeObject(object);
      ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
      ObjectInputStream ois = new ObjectInputStream(bais);
      return ois.readObject();
    }catch (Exception e) {
      e.printStackTrace();
      return null;
    }
 }

An alternative to the deep copy technique

A Java deep clone (deep copy) example

优点:实现简单。

缺点: 性能开销大。

2 使用反射

Java Deep Cloning Library - using reflection - in cases when the classes or the objects you want to clone are out of your control (a 3rd party library) and you can't make them implement Serializable, or in cases you don't want to implement Serializable

results matching ""

    No results matching ""