java - Generics and Class, deciding subclass in constructor -
i want able have (one of) constructor decide implementation of list wants use. code came compiles fine without warnings ide (eclipse) complains on commented line, why , how infer type?
public class genericclasstest<t> { private list<t> list; //stuff... public genericclasstest(class<? extends list> listcreator) throws instantiationexception, illegalaccessexception { this.list = listcreator.newinstance(); // how infer type t? // diamondoperator go? } public static void main(string[] args) throws instantiationexception, illegalaccessexception { genericclasstest<integer> 1 = new genericclasstest<>(arraylist.class); genericclasstest<string> 2 = new genericclasstest<>(linkedlist.class); one.list.add(13); two.list.add("hello"); system.out.println(one.list); system.out.println(two.list); } }
you don't need to. remember type-erasure going replace t object @ runtime anyway. @ runtime have list<object>. therefore, doesn't matter if t part of construction call since ignored anyway. generics compile-time convenience, not lot @ runtime.
Comments
Post a Comment