Deep copy of generic types in Java

How do deep copies (clones) of generic T, e work in Java? Is it possible?

E oldItem;
E newItem = olditem.clone(); // does not work

Solution

The answer is No Because it is impossible to find out which class will replace your generic type E during compilation, unless you are bind it to a type

The cloning method of Java is very shallow. For deep cloning, we need to provide our own implementation

Its solution is to create such contracts

public interface DeepCloneable {
    Object deepClone();
}

And implementers should have their own deep cloning logic

class YourDeepCloneClass implements DeepCloneable {

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

}

It can be called as follows, where generic type E is a bounded type

class Test<E extends DeepCloneable> {

    public void testDeepClone(E arg) {
        E e = (E) arg.deepClone();
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>