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.PS: Keep in mind that the acutalTypeArguments are of type
Type
. They must not be aClass
. In your case it is a Class because your type definition isEventHandler<MyEvent>
.When trying to do anything non-trivial with generics and reflection, consider Guava's
TypeToken
:(Note that the
TypeToken
returned byfindEventType()
could contain much richer type information than aClass
can represent; that's why it's the caller's decision whether to simplify it viagetRawType()
.)