...
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.
...
CWE-374, Passing Mutable Objects to an Untrusted Method | |
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
Item 39, "Make Defensive Copies When Needed" | |
[Security 2006] |
...