I have a class ("Manager") that manages a collection of Objects all rooted in a common superclass ("Managed"). The manager class at times needs to make copies of selected managed objects, but there is no way of knowing which subclass of Managed it is. It seems to me that the best (if not only?) way of doing this is using Cloneable. Then, for any Managed object that I need to copy, I call managedObject.clone(). Of course it must be properly implemented. I've read many admonishments to "just use a copy constructor" or implement myManagedSubClass.copy() method for all subclasses. I don't see how to use a "real" copy constructor, since I need to know the type:
ManagedSubclass copiedObject = new ManagedSubclass(existingManagedSubclassObject);
If I implement the copy() method, I think that would look like this:
class Managed {
public Managed copy() {
Managed newObject = new Managed(Managed other);
// fixup mutable fields in newObject
}
}
But in my usage I'll have to cast the return value to the expected type. If I've forgotten to implement copy() on all Managed subclasses, then I'll end up with a superclass cast to a subclass type. I can't make copy protected visibility on Managed because that is a valid class for direct copying. Even if not the case, I'd have to implement copy on every subclass that can be copied, with all the machinery to handle deep copies of mutable fields, or establish my own protocol of a protected method of some common name taking care of all the mutable fields introduced by that level of superclass.
It seems that despite the general anger and hatred for Cloneable, it is the best way to do what I want. Am I missing something?