vendredi 11 décembre 2015

Java Reflection: Get type parameter of generic interface from implementation class

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
    }
}

Given:

Class myEventHandlerClass = getClazz();

In this clase, T parameter is MyEvent, that is a concrete implementation of Event. How can obtain this using reflection?

I want something like this:

Class myEventHandlerClass = getClazz();
Method handleMethod = myEventhandlerClass.getDeclaredMethod("handle");

Class<?>[] params = method.getParameterTypes();
Class<?> eventConcreteType = params[0];

But myEventhandlerClass.getDeclaredMethod("handle"); throws NoSuchMethodException, since I haven't specified the parameter type, because I just know that is a concrete implementation of Event but I don't know which.





Aucun commentaire:

Enregistrer un commentaire