I made my class immutable by 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 priliminary checkpoints I made when desigining immutable class.
But one question left, my object can still be modified by java reflection, am I right? Or is there any point I missed in the class?
Thanks in advance.
Immutable class in java means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable. We can create our own immutable class as well.
A mutable object can be changed after it's created, and an immutable object can't. In Java, everything (except for strings) is mutable by default: public class IntegerPair { int x; int y; IntegerPair(int x, int y) { this.
The immutable objects are objects whose value can not be changed after initialization. We can not change anything once the object is created. For example, primitive objects such as int, long, float, double, all legacy classes, Wrapper class, String class, etc. In a nutshell, immutable means unmodified or unchangeable.
There's no hiding from reflection - even immutable classes are not immune. There is nothing you can do about it, though, so "cannot be modified through reflection" is not one of the criteria of immutability.
Yes. Reflection can still access / change it. You can't really plan against that. If someone's altering your object with reflection, I would doubt the quality of code they're writing.
Immutable classes are fantastic to ensure thread safe applications. Immutable objects are ALWAYS thread safe. If you're looking for more great information, please read Effective Java. It's a MUST READ for any Java developer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With