2013-10-07 215 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