일반적으로 개발자가 선언한 클래스의 deep copy를 위해서는 Cloneable을 implements 받아서 clone 메쏘드를 구현한다.

deep clone을 하기 위한 단계는 아래와 같습니다.
  1. clone 메쏘드에서 카피할 오브젝트를 shallow copy
  2. 카피할 오브젝트에 레퍼런스 되어 있는 클래스의 오브젝트들도 shallow copy


하지만, 아래는 오브젝트를 직렬화를 통해서 deep copy하는 예제이다.

import java.io.*;
import java.util.*;
import java.awt.*;
public class ObjectCloner {
// so that nobody can accidentally create an ObjectCloner object
private ObjectCloner(){}
// returns a deep copy of an object
static public Object deepCopy(Object oldObj) throws Exception {
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
ByteArrayOutputStream bos =
new ByteArrayOutputStream(); // A
oos = new ObjectOutputStream(bos); // B
// serialize and pass the object
oos.writeObject(oldObj); // C
oos.flush(); // D
ByteArrayInputStream bin =
new ByteArrayInputStream(bos.toByteArray()); // E
ois = new ObjectInputStream(bin); // F
// return the new object
return ois.readObject(); // G
} catch(Exception e) {
System.out.println("Exception in ObjectCloner = " + e);
throw(e);
} finally {
oos.close();
ois.close();
}
}
}


'Java' 카테고리의 다른 글

IllegalMonitorStateException in Object wait(), notify(), notifyall()  (0) 2008/07/03
java.util.Map Iteration  (0) 2008/07/02
deep copy with serialization in java  (0) 2008/07/01
java charset에 대해서..  (1) 2008/06/19
I/O 퍼포먼스 개선  (0) 2008/06/17