Java中的泛型类型的深度拷贝 [英] Deep Copy of a Generic Type in Java
问题描述
泛型类型的深拷贝(克隆)如何在Java中工作?是否有可能?
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
推荐答案
答案是否定的。因为没有办法在编译期间找出哪个类将替换泛型类型 E
,除非你将它绑定到一个类型。
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的克隆方式很浅,对于深层克隆,我们需要提供我们自己的实现。
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();
}
并且实现者应该拥有自己的深度克隆 logic
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();
}
}
可以像下面这样调用,其中泛型类型 E
是一个有界类型
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();
}
}
这篇关于Java中的泛型类型的深度拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!