Immutable class in java

2019-04-26 17:12发布

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.

3条回答
倾城 Initia
2楼-- · 2019-04-26 17:33

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.

查看更多
对你真心纯属浪费
3楼-- · 2019-04-26 17:46

Yes, still it can be modified through reflection. Apart from that it seems you took required care to make it immutable.

查看更多
够拽才男人
4楼-- · 2019-04-26 17:55

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.

查看更多
登录 后发表回答