I have this interface:
public interface EventHandler<T extends Event> {
void handle(T event);
}
And this class implementing it:
public class MyEventHandler implements EventHandler<MyEvent> {
@Override
public void handle(MyEvent event) {
//do something
}
}
In this clase, T
parameter is MyEvent
, that is a concrete implementation of Event
. How can obtain this using reflection?
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With