2013-10-07 155 views
1

我想为一般定义的类编写复制构造函数。我有一个内部类节点,我将用它作为二叉树的节点。当我通过在一个新的对象Java泛型复制构造函数

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> 
} 

我只是不知道如何一般性定义一个拷贝构造函数。

回答

4

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

说一个克隆()方法在这一点上更好?或者你会推荐你的建议? – morganw09dev

+0

@MorganK它取决于。如果只想为实现'Cloneable'的类创建工具,那么应该使用''和'original.clone()'。但由于你的问题是关于复制构造函数(这比'clone'更可取),我发布了可以根据反射做你想要的答案。 – Pshemo

+0

好的。谢谢。你的建议有帮助。 – morganw09dev