2

This code is familiar.

List<Character> list = new ArrayList<Character>();

  // populate the list
  list.add('X');
  list.add('Y');


  // make the list unmodifiable
  List<Character> immutablelist = Collections.unmodifiableList(list);

Now i have a typical Model Class with variables, getters and setters. Can i make that Object immutable,after i have invoked the setters i want? Something like this is my dream...

Person person = new Person();
person.setFirstName("firsName");
person.setLastname("lastName");
// i have a lot to set!!- Person is pretty large

// some way to do this
Person stubborn = Object.immutableObject(person);

I know there is no Object.immutableObject()..But is it possible to achieve something like this??

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • possible duplicate of [How to create immutable objects in Java?](http://stackoverflow.com/questions/6305752/how-to-create-immutable-objects-in-java) – singhakash Mar 13 '15 at 16:38
  • There isn't a way to do exactly what the list implementation does - but you could also clone the object. That way the original object won't be modified if the new one is. – Obicere Mar 13 '15 at 17:14
  • Note same as - How to create immutable objects in Java? I want the object to be mutable - but sometimes i might decide, i have done the necessary editing- no more editing should be done. – searchingforPerfection Mar 16 '15 at 13:15

3 Answers3

4

There's no general way to get this behavior.

You can create an ImmutablePerson class with a constructor that would accept a Person and construct an immutable version of that Person .

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    This is a much cleaner and safer approach than amputating the mutators. For improved usability, `Person` should probably extend `ImmutablePerson` or – even better – both should implement a common interface. – 5gon12eder Mar 13 '15 at 16:46
1

There is no way to do it without doing some work.

You need to either get a compile time check by creating a new immutable object from the mutable one as Eran suggests, add some code for a runtime check, or get a weaker compiler time check by using a split interface e.g

interface ReadOnlyPerson {
  int getX();
} 

interface ModifiablePerson extends ReadOnlyPerson{    
   void setX();
}

class Person implements ModifiablePerson {
}

You can then pass out the immutable reference after construction.

However this pattern does not give a strong guarantee that the object will not be modified as the ReadOnlyPerson reference can be cast etc.

henry
  • 5,923
  • 29
  • 46
0

Sure, just have a boolean flag in the Person object which says if the object is locked for modifications. If it is locked just have all setters do nothing or have them throw exceptions.

When invoking immutableObject(person) just set the flag to true. Setting the flag will also lock/deny the ability to set/change the flag later.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159