abstract - Create dynamic Type Java -


explain problem:

i have super abstract class called first , have lot of class inherit it. want build method "say" "create arraylist of 1 of types inherit first class", i'm not able find solution. example:

public abstract class first{     public first(){    } }  public class firstone extends first{     ........... }  //it's pseudo-code public class myprogramclass{     public creatingmethod(typethatinheritfromfirstclass x ){       return arraylist<typethatinheritfromfirstclass>;    } } 

i insert creatingmethod in program class,but can anywhere(i prefer in first class static method, it's example)

thank time

you use type token:

public class somegenerics {     public static void main(string[] args) {         list<subfirst1> list1 = creatingmethod(subfirst1.class);         list<subfirst2> list2 = creatingmethod(subfirst2.class);     }     public static <t extends first> list<t> creatingmethod(class<t> type) {         return new arraylist<>();     } }  class first {} class subfirst1 extends first {} class subfirst2 extends first {} 

edit per comment:

as have type token, can use creating instances of type. little restriction is, must know constructor use. if - example - have parameterless constructor, can create instances that:

public static <t extends first> list<t> creatingmethod(class<t> type) throws reflectiveoperationexception {     list<t> result = new arraylist<>();     result.add(type.newinstance());     return result; } 

if have constructor parameters (again: sub classes must have same parameterized constructor), must go more difficult way. example string parameter:

public static <t extends first> list<t> creatingmethod(class<t> type, string param) throws reflectiveoperationexception {     list<t> result = new arraylist<>();     constructor<t> constructor = type.getdeclaredconstructor(string.class);     result.add(constructor.newinstance(param));     return result; } 

Comments

Popular posts from this blog

jQuery Mobile app not scrolling in Firefox -

c++ - How to add Crypto++ library to Qt project -

php array slice every 2th rule -