Deep Copy of a Generic Type in Java

南笙酒味 提交于 2019-12-08 19:46:37

问题


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

回答1:


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();
    }
}


来源:https://stackoverflow.com/questions/16436591/deep-copy-of-a-generic-type-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!