I have read Get type of a generic parameter in Java with reflection post and it made me wonder how that would be possible. I used the solution that someone posted and using
The method you described does ONLY work, when the Generic Type is Set due to inheritance, because then its known during compile time:
public class SomeClass{
}
public class SpecificClass extends SomeClass{
}
For this example, you can use the method and you'll get back "String.class".
If you are creating instances on the fly it won't work:
SomeClass s = new SomeClass(); //wont work here.
Some common work around is, to pass the actual class as a parameter for later reference:
public class SomeClass{
Class clazz
public SomeClass(Class clazz){
this.clazz = clazz;
}
public Clazz getGenericClass(){
return this.clazz;
}
}
usage:
SomeClass someClass= new SomeClass(String.class);
System.out.println(someClass.getGenericClass()) //String.class
Actually you don't even need the Generic type for such an scenario, because Java would do the same thing, as if you would handle the "T" as Object. Only advantage is, that you can define getter and Setter of T and don't need to typecast Objects all the time. (Because Java is doing that for you)
(It's called Type Erasure)