Mutable classes are those which when instantiated, return a reference such that the contents of the instance (instance members) can be altered. It is important to provide means for creating copies of mutable classes to allow passing their respective class objects to untrusted code. The defensive copying ensures that untrusted code cannot manipulate the object's state. The copying mechanism can be advertised by overriding java.lang.Object
's clone()
method. However, providing a clone()
method by itself, does not obviate the need to create defensive copies when receiving input from untrusted code and returning values to the same (see FIO31-J. Defensively copy mutable inputs and mutable internal components and OBJ37OBJ11-J. Defensively copy private mutable class members before returning their references). Only a trusted caller can be expected to responsibly call the overriding clone()
method before passing instances to untrusted code.
...
Always provide mechanisms to create copies of the instances of a mutable class. This compliant solution implements the Cloneable
interface and overrides the clone
method to create a deep copy of the object. If untrusted code can call accessor methods, it is also advisable to copy all the mutable objects that are passed in before they are stored in the class (FIO31-J. Defensively copy mutable inputs and mutable internal components) or returned from any methods (OBJ37OBJ11-J. Defensively copy private mutable class members before returning their references). This is because untrusted code cannot be expected to call the object's clone()
method to operate on the copy. This compliant solution provides a clone()
method to trusted code and also guarantees that the state of the object cannot be compromised when the accessor method is called directly from untrusted code.
...
OBJ35-J. Use checked collections against external code 08. Object Orientation (OBJ) OBJ37OBJ11-J. Defensively copy private mutable class members before returning their references