Java Generics Copy Constructor -
i'm wanting code copy constructor generically defined class. have inner class node, going use nodes binary tree. when pass in a new object
public class treedb <t extends object> { //methods , such public t patient; patient = new t(patient2); //this line throwing error //where patient2 of type <t> }
i don't know how generically define copy constructor.
t
can't guarantee class represents have required constructor can't use new t(..)
form.
i not sure if need if sure class of object want copy have copy constructor can use reflection like
public class test<t> { public t createcopy(t item) throws exception {// here should // thrown more detailed exceptions decided reduce them // readability class<?> clazz = item.getclass(); constructor<?> copyconstructor = clazz.getconstructor(clazz); @suppresswarnings("unchecked") t copy = (t) copyconstructor.newinstance(item); return copy; } }
//demo myclass 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()); }
Comments
Post a Comment