Java中的不可变类 [英] Immutable class in java

查看:58
本文介绍了Java中的不可变类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循所有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.

还有一个问题,我的对象仍然可以通过java反射进行修改,对吗? 还是我在课堂上错过了一点?

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?

谢谢.

推荐答案

没有任何隐藏的东西-甚至不可变的类也不能幸免.但是,您对此无能为力,因此无法通过反射进行修改"不是不变性的标准之一.

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.

这篇关于Java中的不可变类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆