How can I obtain the type parameter of a generic interface from an implementing class?

前端 未结 2 1347
萌比男神i
萌比男神i 2021-01-12 14:53

I have this interface:

public interface EventHandler {
    void handle(T event);
}

And this class implementing it:

2条回答
  •  温柔的废话
    2021-01-12 15:03

    Resolve the type of T by the generic interface. E.g.

    public interface SomeInterface {
    }
    
    public class SomeImplementation implements SomeInterface {
    
        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.

提交回复
热议问题