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());
}
說一個克隆()方法在這一點上更好?或者你會推薦你的建議? – morganw09dev
@MorganK它取決於。如果只想爲實現'Cloneable'的類創建工具,那麼應該使用''和'original.clone()'。但由於你的問題是關於複製構造函數(這比'clone'更可取),我發佈了可以根據反射做你想要的答案。 –
Pshemo
好的。謝謝。你的建議有幫助。 – morganw09dev