Immutability helps to supporting support security reasoning. It is safe to share immutable objects , without risk that the recipient can modify them [Mettler 2010B2010b].
Programmers often incorrectly assume that declaring a field or variable final
makes the referenced object immutable. Declaring variables that have a primitive type to be final
does prevent changes to their values after initialization (by normal Java processing). However, when the variable has a reference type, the presence of a final
clause in the declaration only makes the reference itself immutable. The final
clause has no effect on the referenced object. Consequently, the fields of the referenced object may be mutable. For example, according to the Java Language Specification [JLS 2011], §4.12.4, "final
Variables,",
If a
final
variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.This applies also to arrays, because arrays are objects; if a
final
variable holds a reference to an array, then the components of the array may be changed by operations on the array, but the variable will always refer to the same array.
Similarly, a final
method parameter obtains an immutable copy of the object reference. Again, this has no effect on the mutability of the referenced data.
...
Related Guidelines
CWE ID 607, "Public Static Final Field References Mutable Object"Public static final field references mutable object |
Bibliography
Item 13: , "Minimize the accessibility Accessibility of classes Classes and membersMembers" | |||
Chapter 6, "Interfaces and Inner Classes" | |||
[JLS 2011] |
| ||
Class Properties for Security Review in an Object-Capability Subset of Java |