I am trying to get a Class<?> instance for the generic type. There is a lot of answers how to do that, but I am getting the error:
java.lang.ClassCastException: class java.lang.Class cannot be cast to class java.lang.reflect.ParameterizedType (java.lang.Class and java.lang.reflect.ParameterizedType are in module java.base of loader 'bootstrap')
I use Java 17. The code to reproduce the error:
class GenericTypeTest {
@Test
void showsTheError() {
Generic<String> g = new Generic<>();
assertEquals(String.class, g.getType());
}
static class Generic<T> {
Class<?> getType() {
Type type = getClass().getGenericSuperclass();
ParameterizedType paramType = (ParameterizedType) type;
return (Class<?>) paramType.getActualTypeArguments()[0];
}
}
}
The superclass of Generic<T>
is Object
, which isn't generic.
You need to subclass Generic
for this to work:
Generic<String> g = new Generic<>() {};
Consider making Generic
abstract
in order to force it to be subclassed in order to instantiate it.