As to whether the tool is useful in real life, it depends on why you need immutability (as indicated in this article, you check at runtime or through verification or protection against malicious code, or simply guarantee that your own code is immutable ?). The simplest assurance that a class is immutable, if you manually view it, is that all field entries occur only in the constructor, or that all fields are final (or both). A.
But this is still limited, because "final Object x" ensures that your link does not change, but does not mean that the link object does not change. As Adam evades, if this list can change the list, which can cause thread problems in your (otherwise immutable) class. And if you used the value in the list to determine your hash code (you use x.hashCode () as part of generating your own hash code), then your hash code will change, violating other rules (therefore the immutable representation of the list isnβt even enough).
If your immutable class is not affected by the changes to the held object, then this may be good for your purposes.
A run-time check must be limited in time / depth / limit, therefore it cannot be perfect. Those tools (or any similar execution approach) have some use, but it really depends on why you need to define immutability. If you can specify immutability as part of an API requirement, detect violations of this rule (for example, hashCode of object changes) and throw an exception when they change, then you do not need to detect it yourself. Or trust your subscribers. If you are trying to write an immutable class, these tools do not help at all. If you are really looking for thread safety, immutability is not an adequate answer.
This is not a satisfactory answer to this question (which is good), but I think that in most cases this becomes the wrong question if you consider the problem more closely.
source share