Get generic type of class at runtime Get generic type of class at runtime java java

Get generic type of class at runtime


As others mentioned, it's only possible via reflection in certain circumstances.

If you really need the type, this is the usual (type-safe) workaround pattern:

public class GenericClass<T> {     private final Class<T> type;     public GenericClass(Class<T> type) {          this.type = type;     }     public Class<T> getMyType() {         return this.type;     }}


I have seen something like this

private Class<T> persistentClass;public Constructor() {    this.persistentClass = (Class<T>) ((ParameterizedType) getClass()                            .getGenericSuperclass()).getActualTypeArguments()[0]; }

in the hibernate GenericDataAccessObjects Example


Generics are not reified at run-time. This means the information is not present at run-time.

Adding generics to Java while mantaining backward compatibility was a tour-de-force (you can see the seminal paper about it: Making the future safe for the past: adding genericity to the Java programming language).

There is a rich literature on the subject, and some people are dissatisfied with the current state, some says that actually it's a lure and there is no real need for it. You can read both links, I found them quite interesting.