Java Generics Copy构造函数
发布时间:2020-12-15 04:14:13 所属栏目:Java 来源:网络整理
导读:我想为一般定义的类编写一个拷贝构造函数.我有一个内部类Node,我将其用作二叉树的节点.当我传入一个新的对象时 public class treeDB T extends Object { //methods and such public T patient; patient = new T(patient2); //this line throwing an error //
我想为一般定义的类编写一个拷贝构造函数.我有一个内部类Node,我将其用作二叉树的节点.当我传入一个新的对象时
public class treeDB <T extends Object> { //methods and such public T patient; patient = new T(patient2); //this line throwing an error //where patient2 is of type <T> } 我只是不知道如何一般地定义一个复制构造函数. 解决方法
T不能保证它所代表的类将具有必需的构造函数,因此您不能使用新的T(..)形式.
我不确定这是否是你需要的但如果你确定要复制的对象类将有复制构造函数那么你可以使用像 public class Test<T> { public T createCopy(T item) throws Exception {// here should be // thrown more detailed exceptions but I decided to reduce them for // readability Class<?> clazz = item.getClass(); Constructor<?> copyConstructor = clazz.getConstructor(clazz); @SuppressWarnings("unchecked") T copy = (T) copyConstructor.newInstance(item); return copy; } } //demo for MyClass that will have copy constructor: // public MyClass(MyClass original) public static void main(String[] args) throws Exception { MyClass mc = new MyClass("someString",42); Test<MyClass> test = new Test<>(); MyClass copy = test.createCopy(mc); System.out.println(copy.getSomeString()); System.out.println(copy.getSomeNumber()); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |