开发者

How do I make defensive copy of an object?

How do I make defensive copies of a Mutable Object which contains a mutable field in an Immutable Object?

class ImmutableObject {

  private final MutableObject immutable_field;

  ImmutableObject(MutableObject y) {
    this.immutable_field = y;
  }
}

class MutableObject {

  public int mutable_field;
}
  • The MutableObject does not have a constructor that lets me set the field.
  • The MutableObject's current state should be captured in the Immutable Object and nev开发者_开发百科er changed.


What you need to do is in

  MutableObject return_immutable_field() {
    return immutable_field;
  }

Change to:

  MutableObject return_immutable_field() {
    MutableObject tmp = new MutableObject();
    tmp.mutable_field = immutable_field.mutable_field;
    return tmp;
  }

For an explanation see http://www.javapractices.com/topic/TopicAction.do?Id=15


Well, assuming that there is nothing to be done about the declaration of the mutable object class, one could leverage reflection (Class.newIntance() and Class.getFields()) to create a new object and copy field values. You could also implement deep copying in this manner. If the class supports serialization, then another hackish approach would be to serialize the object and then save a deserialized copy. If it is possible to fix the design of the mutable object, though, that would be a better approach.

Edit
For the particular example that you've given, Romain's answer does what you want. If you have a general mutable object that doesn't provide a mechanism for copying it and for which the type may not be known until later, then the reflection approach is how one would implement a copy mechanism.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜