简体   繁体   English

Java Generics Copy构造函数

[英]Java Generics Copy Constructor

I'm wanting to code a copy constructor for a generically defined class. 我想为一般定义的类编写一个拷贝构造函数。 I have an inner class Node, which I am going to use as the nodes for a binary tree. 我有一个内部类Node,我将其用作二叉树的节点。 When I pass in aa new Object 当我传入一个新的对象时

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

I just don't know how to generically define a copy constructor. 我只是不知道如何一般地定义一个复制构造函数。

T can't guarantee that class it represents will have required constructor so you can't use new T(..) form. T不能保证它所代表的类将具有必需的构造函数,因此您不能使用new T(..)形式。

I am not sure if that is what you need but if you are sure that class of object you want to copy will have copy constructor then you can use reflection like 我不确定这是否是你需要的但如果你确定要复制的对象类将有复制构造函数那么你可以使用像

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM