Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Note that the clone() method must manually clone the Date object. This step is usually unnecessary when the object contains only primitive fields or fields that refer to immutable objects. However, when the fields contain data such as unique identifiers or object creation times, the clone() method must calculate and assign appropriate new values for such fields [Bloch 2008].

Mutable classes that define a clone() method must be declared final. This ensures that untrusted code cannot declare a subclass that overrides the clone() method to create a spurious instance. The clone() method should copy all internal mutable state as necessary — in this compliant example, the Date object.

...

Callers can use the clone() method to obtain an instance of such a mutable class. The 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 there might not be an accessible copy method 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. Finally, the clone() method must create and return a new instance of the enclosing class (MutableClass) using the newly created member instance (d) [SCG 2009].

Mutable classes that define a clone() method must be declared final.

...

MITRE CWE

CWE-374. Passing Mutable Objects to an Untrusted Method

 

CWE-375. Returning a Mutable Object to an Untrusted Caller

Secure Coding Guidelines for the Java Programming Language, Version 3.0

Guideline 2-3. Support copy functionality for a mutable class

Bibliography

[API 2006]

Method clone()

[Bloch 2008]

Item 39. Make defensive copies when needed, Item 11. Override clone judiciously

[Security 2006]

 

...