java - How to get (generic) type from class object -


i this:

get "class" object generic type t

but other way round. type of class objects. in pseudocode want this:

public class exampleclass {      public static final class<?>[] classes = new class[]{myclass1.class,     myclass2.class, myclass3.class, myclass4.class, myclass5.class};      public void mymethod() {         (class<?> c : databaseconfigutils.classes ) {             myobjectdao<c.gettype(), integer> myobjectdao = getmyobjectdao(c);             arraylist<c.gettype()> list = myobjectdao.queryall();             (c.gettype() element : list) {                 processelement(element);             }          }     }      public <t> myobjectdao<t, integer> getmyobjectdao(class<t> c) {         return dosomething(c);     } } 

but there nothing class.gettype(). how type of class object?

your generic method getmyobjectdao seems answer own question. if have variable wildcard in type, can use generic helper method whenever need refer type in code. can refactor code this:

public class exampleclass {      public static final class<?>[] classes = new class[]{myclass1.class,         myclass2.class, myclass3.class, myclass4.class, myclass5.class};      public void mymethod() {         (class<?> c : databaseconfigutils.classes ) {             act(c);             }     }      private <t> void act(class<t> c) {         myobjectdao<t, integer> myobjectdao = getmyobjectdao(c);         arraylist<t> list = myobjectdao.queryall();         (t element : list) {             processelement(element);         }     }      public <t> myobjectdao<t, integer> getmyobjectdao(class<t> c) {         return dosomething(c);     } } 

it important aware of limitations of this. suppose have variable of type list<?>. while is possible use private generic helper method enable treat list<t> , use type t in code, type erasure means can't query type t @ runtime. of following illegal

if (t == string) { //do something; }  if (t.class == string.class) { //do }  if (a instanceof t) { //do } 

the usual workaround make 1 of arguments helper method class<t> object, because can do

if (clazz == string.class) { //do } 

(note not work if t generic type, because cannot write list<string>.class, example. there workaround called super type tokens this.)

since objects using are class objects, type erasure should not cause problems @ all.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

apache - setting document root in antoher partition on ubuntu -