Mutable classes are those which when instantiated, return a reference such that the contents of the instance 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 copying ensures that untrusted code cannot manipulate the object's state. The copying mechanism can be offered advertised by overriding java.lang.Object
's clone()
method. However, providing a clone()
method by itself, does not eliminate obviate the need to create defensive copies when receiving input from untrusted code and returning values to the same. 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 it is possible that the accessor methods can be called from untrusted code, 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 (OBJ37-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 not only provides a clone()
method for to trusted code but and also guarantees that the state of the object cannot be compromised when the accessor method is called directly from untrusted code.
...
Wiki Markup |
---|
At times, a mutable class's member class field is declared {{final}} with no accessible copy methods. Callers can use the {{clone()}} method to obtain an instance of the mutable class. This {{clone()}} method must create a new instance of the {{final}} member class and copy the original state to it. The new instance is necessary because no accessible copy method may be available in the member class. If the member class evolves in the future, it is critical to include the new state in the manual copy. \[[SCG 07|AA. Java References#SCG 07]\] |
...