我想为一个通用定义的类编写一个复制构造函数。我有一个内部类节点,我将使用它作为二叉树的节点。当我传入一个新对象时
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
不能保证它所代表的类将具有必需的构造函数,因此您不能使用 new 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());
}
关于Java泛型复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19216136/