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

前端 未结 2 1327
萌比男神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:25

    When trying to do anything non-trivial with generics and reflection, consider Guava's TypeToken:

    private interface Event {}
    
    private interface EventHandler {
        void handle(T event);
    }
    
    TypeToken findEventType(final Class handlerClass) throws Exception {
        final TypeToken handlerTypeToken = TypeToken.of(handlerClass);
        final Invokable method = handlerTypeToken.method(EventHandler.class.getDeclaredMethod("handle", Event.class));
        return method.getParameters().get(0).getType();
    }
    
    public void testExploreGuavaTypeTokens() throws Exception {
        class MyEvent implements Event {}
    
        class MyEventHandler implements EventHandler {
            @Override public void handle(final MyEvent event) {}
        }
    
        assertEqual(MyEvent.class, findEventType(MyEventHandler.class).getRawType());
    }
    

    (Note that the TypeToken returned by findEventType() could contain much richer type information than a Class can represent; that's why it's the caller's decision whether to simplify it via getRawType().)

提交回复
热议问题