【发布时间】:2023-03-30 01:20:01
【问题描述】:
我这里有一个Handler 类,它应该处理某种类型的Events:
public interface Handler<E extends Event>
{
public void handle(E event);
@SuppressWarnings("unchecked")
public default Class<E> getEventType()
{
for(Method method: this.getClass().getDeclaredMethods())
{
if(method.getName().equals("handle")) return (Class<E>)method.getParameterTypes()[0];
}
throw new NullPointerException("Couldn't find the 'handle' method in this handler.");
}
}
如您所见,默认情况下,当您执行 getEventType() 时,它会通过返回 handle() 方法的第一个参数类型(而不是 Handler显式返回它)。这适用于以下 JUnit 测试:
public static class EmptyEvent extends Event
{
public void test() { }
}
public static Handler<EmptyEvent> genericHandler = new Handler<EmptyEvent>()
{
@Override
public void handle(EmptyEvent event)
{
}
};
@Test
public void testEventGenerics()
{
//prints the name of EmptyEvent
System.out.println(genericHandler.getEventType());
}
Intellij IDEA 告诉我可以将 genericHandler 简化为 lambda 表达式,所以我这样做了:
public static class EmptyEvent extends Event
{
public void test() { }
}
public static Handler<EmptyEvent> genericHandler = event -> { };
@Test
public void testEventGenerics()
{
//prints the name of the base Event class
System.out.println(genericHandler.getEventType());
}
但是,测试会打印出Event 的名称,而不是EmptyEvent。
所以我的问题是,有没有办法明确定义 lambda 表达式的泛型参数类型?
我尝试做这样的事情,但它什么也没做(也是一个错误)
public static Handler<EmptyEvent> genericHandler = (EmptyEvent)event -> { };
【问题讨论】: