Immutable class in java

三世轮回 提交于 2019-12-18 05:54:36

问题


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.


回答1:


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.




回答2:


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:


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



来源:https://stackoverflow.com/questions/12985059/immutable-class-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!