技術メモのかけら

内容はもとより調べたことすら忘れてしまうので個人的なメモです。とにかく短く、結論だけ書いていきます。

簡単なオブジェクトのディープコピー

オブジェクトを楽にディープコピーするコード。
性能面の問題やSerializableなメンバーじゃないとコピーされないとか問題があるけどメモ。

private <T> T deepCopy(final T target) {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(target);

    final ObjectInputStream ois = new ObjectInputStream(
        new ByteArrayInputStream(bos.toByteArray()));
    return (T) ois.readObject();
}