/**
* 引数のオブジェクトのディープコピーを返却します。
* ※コピー元のオブジェクトおよび、その要素はjava.io.Serializableを実装する必要があります。
* @param obj コピー元オブジェクト
* @return 引数のディープコピー
* @throws IOException
* @throws ClassNotFoundException
*/
public static Object deepCopy(Serializable obj) throws IOException, ClassNotFoundException {
if (obj == null) {
// 引数がnullの場合
return null;
}
// Serializableを実装したClassのディープコピーを作成し、返却する。
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(obj);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
return in.readObject();
}
法案②
public class ob implements Cloneable {
public ob(){}
public Object clone() {
try {
return super.clone() ;
} catch (CloneNotSupportedException e) {
throw new InternalError(e.getMessage());
}
}
}