Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable class in java

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.

like image 228
Satheesh Cheveri Avatar asked Oct 20 '12 03:10

Satheesh Cheveri


People also ask

What is an immutable class in Java?

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.

What is mutable and immutable class in Java?

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.

What is immutable with examples?

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.


2 Answers

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.

like image 73
Sergey Kalinichenko Avatar answered Oct 15 '22 08:10

Sergey Kalinichenko


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.

like image 24
Kurtymckurt Avatar answered Oct 15 '22 09:10

Kurtymckurt