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