8

How does deep copies (clones) of generic types T, E work in Java? Is it possible?

E oldItem;
E newItem = olditem.clone(); // does not work
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Michael Dorner
  • 17,587
  • 13
  • 87
  • 117
  • check this out: http://stackoverflow.com/questions/64036/how-do-you-make-a-deep-copy-of-an-object-in-java – madoke May 08 '13 at 09:14
  • There is no general way to clone an object in Java. Specific classes have public clone() methods, but here you don't know which class it is. – newacct May 08 '13 at 19:56

1 Answers1

5

The answer is no. Cause there is no way to find out which class will replace your generic type E during compile time, unless you Bind it to a type.

Java way of cloning is shallow, for deep cloning, we need to provide our own implementation

The work-around for it, is to create a contract like this

public interface DeepCloneable {
    Object deepClone();
}

and an implementor should be having its own deep-clone logic

class YourDeepCloneClass implements DeepCloneable {

    @Override
    public Object deepClone() {
        // logic to do deep-clone
        return new YourDeepCloneClass();
    }

}

and it can be called like below, where the generic type E is a bounded type

class Test<E extends DeepCloneable> {

    public void testDeepClone(E arg) {
        E e = (E) arg.deepClone();
    }
}
sanbhat
  • 17,522
  • 6
  • 48
  • 64