[英]In Java is it possible to assign a method reference to a variable whose class has a generic type?
Let's say we've got the following classes: 假设我们有以下课程:
interface Event {
}
@FunctionalInterface
interface EventListener<T extends Event> {
void onEvent(T event);
}
class Service {
class ServiceEvent implements Event {
}
public void onServiceEvent(ServiceEvent event) {
}
}
Why does the following assignment compile without any problems: 为什么以下任务编译没有任何问题:
Service service = new Service();
EventListener<ServiceEvent> listener = service::onServiceEvent;
but this one: 但是这一个:
Service service = new Service();
EventListener<? extends Event> anotherListener = service::onServiceEvent;
fails with this compile error: 失败并出现此编译错误:
Error: java: incompatible types: invalid method reference incompatible types: Event cannot be converted to Service.ServiceEvent
public void onServiceEvent(ServiceEvent event) {}
This accepts only ServiceEvent
parameters. 这只接受ServiceEvent
参数。 Just like: 就像:
EventListener<ServiceEvent> listener = service::onServiceEvent;
but: 但:
EventListener<? extends Event> anotherListener
Can accept not only ServiceEvent
but also all subtypes of the Event
type. 不仅可以接受ServiceEvent
,还可以接受Event
类型的所有子类型。 Hence, the type mismatch 因此,类型不匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.