Reflection for Class of generic parameter in Java?

This can be achieved with reflection only because you explicitly used String, otherwise this information would’ve been lost due to type erasure.

ParameterizedType t = (ParameterizedType) MyClass.class.getGenericSuperclass(); // OtherClass<String>
Class<?> clazz = (Class<?>) t.getActualTypeArguments()[0]; // Class<String>

Leave a Comment