I need to implement a deep clone in one of my objects which has no superclass.
What is the best way to handle the checked CloneNotSupportedException thrown by the superclass (which is Object)?
A coworker advised me to handle it the following way:
@Override
public MyObject clone()
{
MyObject foo;
try
{
foo = (MyObject) super.clone();
}
catch (CloneNotSupportedException e)
{
throw new Error();
}
// Deep clone member fields here
return foo;
}
This seems like a good solution to me, but I wanted to throw it out to the StackOverflow community to see if there are any other insights I can include. Thanks!
Do you absolutely have to use
clone? Most people agree that Java’scloneis broken.Josh Bloch on Design – Copy Constructor versus Cloning
You may read more discussion on the topic in his book Effective Java 2nd Edition, Item 11: Override
clonejudiciously. He recommends instead to use a copy constructor or copy factory.He went on to write pages of pages on how, if you feel you must, you should implement
clone. But he closed with this:The emphasis was his, not mine.
Since you made it clear that you have little choice but to implement
clone, here’s what you can do in this case: make sure thatMyObject extends java.lang.Object implements java.lang.Cloneable. If that’s the case, then you can guarantee that you will NEVER catch aCloneNotSupportedException. ThrowingAssertionErroras some have suggested seems reasonable, but you can also add a comment that explains why the catch block will never be entered in this particular case.Alternatively, as others have also suggested, you can perhaps implement
clonewithout callingsuper.clone.