0

Suppose I have a class which I have made immutable by following the steps below only.

  1. Mark class as final which has two fields one is String and other is List type.
  2. mark fields as private but NOT final.
  3. Creating a new ArrayList in constructor by the parameter passed and assign to the private List field.
  4. Make the getter of the List field return a Deep Copy always.
  5. Returning the String field by simply "return name".

As per my understanding I have made this class Immutable and its instances cannot be changed.

But what could still be the loopholes, security issues and ways where the immutability of this class can be broken/compromised/violated.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
Ankit_ceo2
  • 317
  • 1
  • 6
  • 14
  • 1
    See: [Immutable class in java](https://stackoverflow.com/questions/12985059/immutable-class-in-java) and if you plan to make it serializable see [How can serialisation/deserialisation break immutability?](https://stackoverflow.com/questions/17603412/how-can-serialisation-deserialisation-break-immutability) – lealceldeiro Jun 05 '19 at 09:19
  • Reflection would be the easiest way. – Robby Cornelissen Jun 05 '19 at 09:20
  • Is it possible using Unsafe? – dan1st Jun 05 '19 at 09:21
  • @RobbyCornelissen Actually I do not think my question is duplicate coz if you look at the point number 2 making fields not FINAL, so could there be anything apart from reflection break this? – Ankit_ceo2 Jun 05 '19 at 09:27
  • There are some short-comings I hope others might list. Especially how far should "immutable" go for containers (seeing your deep copy)? But I want to just mention `Collections.unmodifiableList` and `ArrayList.trimToSize`. – Joop Eggen Jun 05 '19 at 09:29
  • As far as I can tell, it doesn't change anything, but I'm willing to reopen the question if you like. – Robby Cornelissen Jun 05 '19 at 09:29

0 Answers0