Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I obtain the type parameter of a generic interface from an implementing 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
    }
}

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

like image 963
Héctor Avatar asked Dec 11 '15 11:12

Héctor


1 Answers

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

like image 162
René Link Avatar answered Nov 15 '22 17:11

René Link