How to make a protective copy of an object?

How to make protective copies of a Mutable object that 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;
}
  • There is no constructor in MutableObject that allows me to set a field.
  • The current state of a MutableObject must be fixed in an immutable object and never change.
+3
source share
2 answers

What you need to do is

  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

+7
source

, , , (Class newIntance() Class. getFields()), . . , , . , , .


, , , . , , , .

+4

Source: https://habr.com/ru/post/1748086/


All Articles