スマートなDeepCopy

ディープコピー

import org.apache.commons.lang.SerializationUtils;

  public SampleBean deepCopy(SampleBean src) {
    SampleBean dest = (SampleBean)SerializationUtils.clone(src);
    return dest;
  }

コピーするクラスは、java.io.Serializable を実装している必要があります。

内部では、シリアライズ → デシアライズをすることで、ディープコピーを実現しています。

2007-06-10

あー、こんな簡単なんですね…。自分、コピーコンストラクタを定義した上で、こんな変なことしてました…。

  public SampleBean(final SampleBean source) {
    // プロパティを1つ1つコピー
  }

  public SampleBean copy() {
    SampleBean dest = null;
    try {
      final Constructor con = this.getClass().getConstructor(new Class[] { this.getClass() });
      dest = (SampleBean) con.newInstance(this);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return dest;
  }

結果は同じになるかどうか未検証。でも前者の方が絶対簡単…。