I have a generics class, Foo
. In a method of Foo
, I want to get the class instance of type T
, but I just can\'t call T.
I found a generic and simple way to do that. In my class I created a method that returns the generic type according to it's position in the class definition. Let's assume a class definition like this:
public class MyClass {
}
Now let's create some attributes to persist the types:
public class MyClass {
private Class aType;
private Class bType;
private Class cType;
// Getters and setters (not necessary if you are going to use them internally)
}
Then you can create a generic method that returns the type based on the index of the generic definition:
/**
* Returns a {@link Type} object to identify generic types
* @return type
*/
private Type getGenericClassType(int index) {
// To make it use generics without supplying the class type
Type type = getClass().getGenericSuperclass();
while (!(type instanceof ParameterizedType)) {
if (type instanceof ParameterizedType) {
type = ((Class>) ((ParameterizedType) type).getRawType()).getGenericSuperclass();
} else {
type = ((Class>) type).getGenericSuperclass();
}
}
return ((ParameterizedType) type).getActualTypeArguments()[index];
}
Finally, in the constructor just call the method and send the index for each type. The complete code should look like:
public class MyClass {
private Class aType;
private Class bType;
private Class cType;
public MyClass() {
this.aType = (Class) getGenericClassType(0);
this.bType = (Class) getGenericClassType(1);
this.cType = (Class) getGenericClassType(2);
}
/**
* Returns a {@link Type} object to identify generic types
* @return type
*/
private Type getGenericClassType(int index) {
Type type = getClass().getGenericSuperclass();
while (!(type instanceof ParameterizedType)) {
if (type instanceof ParameterizedType) {
type = ((Class>) ((ParameterizedType) type).getRawType()).getGenericSuperclass();
} else {
type = ((Class>) type).getGenericSuperclass();
}
}
return ((ParameterizedType) type).getActualTypeArguments()[index];
}
}