I need to equip my class with polymorphic cloning (deep copy), i.e. I need something like this to work:
SuperType original = new SubType();
SuperType copy = original.clone();
where original.clone()
can be substituted by any mechanism to create a deep copy, and the actual type of copy
shall be SubType
, because original
is also a SubType
.
Is the clone()
method and Cloneable
interface the only way to achieve this? Factory methods and copy constructors cannot by used, since the actual class is known only in run time, right? Are there any other suggested methods except those serialize-deserialize approaches, and the Java deep-cloning library which is IMHO even worse black magic than the clone()
method?
Thanks, Petr
new SubType(original)
which I cannot since I do not know in time of writing the code if original is actually of classSubType
, orSubType2
, orSubSubType
. – Cinchonize