Immutable class in java

I made my class immutable following all Java standards

A. Defined class as final B. declared all fields as private and final C. No setter method D. No method changes the state of object E. declared all method as final F. Safer/defencieve copying of collection/ non mutable object fields. 

These are the preliminal breakpoints that I did when I discussed the immutable class.

But one question remains, my object can still be modified using java reflection, right? Or is there some point that I missed in class?

Thanks in advance.

+6
source share
3 answers

Not hiding from reflection - even immutable classes are not protected. But you can’t do anything about it, therefore, “cannot be changed by reflection” is not one of the criteria for immutability.

+7
source

Yes, it can be changed using reflection. In addition, it seems that you have taken the necessary care to make it unchanged.

+1
source

Yes. A reflection can still access / modify it. You cannot do this. If someone changes your object with reflection, I would doubt the quality of the code they write.

Unmatched classes are fantastic for providing thread-safe applications. Immutable objects are ALWAYS thread safe. If you are looking for more information, read Effective Java. This SHOULD READ for any Java developer.

+1
source

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


All Articles