Java 中泛型的深拷贝
编程 65
泛型类型 T, E
的深拷贝(克隆)在 Java 中如何工作?可能吗?
E oldItem;
E newItem = olditem.clone(); // does not work
-
答案是否定的。因为没有办法在编译期间找出哪个类将替换您的通用类型
E
,除非您 Bind it to a type .Java的克隆方式很浅,如果要深克隆,需要自己提供实现
解决方法是创建这样的合约
public interface DeepCloneable { Object deepClone(); }
并且实现者应该有自己的深度克隆逻辑
class YourDeepCloneClass implements DeepCloneable { @Override public Object deepClone() { // logic to do deep-clone return new YourDeepCloneClass(); } }
它可以像下面这样调用,其中泛型
E
是有界类型class Test<E extends DeepCloneable> { public void testDeepClone(E arg) { E e = (E) arg.deepClone(); } }
2025-04-13 15:07:04