Versions Compared

Key

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

...

This approach is useful when the instance fields are declared final. Callers request a copy by invoking the copy constructor with an existing MutableClass instance as its argument.

...

This approach is useful when the instance fields are declared final.

Compliant Solution (clone())

...

When a mutable class's instance fields are declared final and lack accessible copy methods, provide a clone() method, as shown in this compliant solution:

...

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

Compliant Solution (Unmodifiable Date Wrapper)

If cloning or copying a mutable object is infeasible or expensive, one alternative is to create an unmodifiable immutable view class. This class overrides mutable methods to throw an exception, protecting the mutable class.

...

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 LanguageSE, Version 35.0

Guideline 2-3. 6-4 / MUTABLE-4: Support copy functionality for a mutable class

Bibliography

[API 20062014]

Method clone()

[Bloch 2008]

Item 39, "Make Defensive Copies When Needed"
Item 11, "Override Clone Judiciously"

[Security 2006] 

...