How can I obtain the type parameter of a generic interface from an implementing class?
Resolve the type of T
by the generic interface. E.g.
public interface SomeInterface<T> {
}
public class SomeImplementation implements SomeInterface<String> {
public Class getGenericInterfaceType(){
Class clazz = getClass();
ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericInterfaces()[0];
Type[] typeArguments = parameterizedType.getActualTypeArguments();
Class<?> typeArgument = (Class<?>) typeArguments[0];
return typeArgument;
}
}
public static void main(String[] args) {
SomeImplementation someImplementation = new SomeImplementation();
System.out.println(someImplementation.getGenericInterfaceType());
}
PS: Keep in mind that the acutalTypeArguments are of type Type
. They must not be a Class
. In your case it is a Class because your type definition is EventHandler<MyEvent>
.