How to get the class of generic type T in Java?
In Java, due to the limitations of type erasure, it is not possible to directly obtain the Class object of a generic type. However, there are two ways to obtain the Class object of a generic type.
- Obtain the Class object of a generic type by passing a Class parameter.
public class MyClass<T> {
private Class<T> type;
public MyClass(Class<T> type) {
this.type = type;
}
public Class<T> getType() {
return type;
}
}
// 使用示例
MyClass<String> myClass = new MyClass<>(String.class);
Class<String> stringClass = myClass.getType();
In the example above, the Class object of the generic type is obtained by passing a Class parameter in the constructor and saved in a member variable, then accessed using the getType method.
- Obtain the Class object of a generic type through reflection.
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class MyClass<T> {
public Class<T> getType() {
Type type = getClass().getGenericSuperclass();
ParameterizedType paramType = (ParameterizedType) type;
Type[] actualTypeArguments = paramType.getActualTypeArguments();
return (Class<T>) actualTypeArguments[0];
}
}
// 使用示例
MyClass<String> myClass = new MyClass<String>();
Class<String> stringClass = myClass.getType();
In the above example, by using reflection, we can obtain the Class object of a generic type. First, we use the getClass method to get the Class object of the current object, then use the getGenericSuperclass method to obtain the Type object of the superclass of that Class object. Next, we check if this Type object is of ParameterizedType type, if so, we use the getActualTypeArguments method to get an array of Type objects representing the actual type parameters, and finally, we cast it to a Class object to obtain the Class object of the generic type.
It is important to note that when obtaining the Class object of a generic type using the second method, a parameterless constructor must be implemented in the subclass, otherwise a ClassCastException exception will be thrown.