繁体   English   中英

在Java中,是否可以为其类具有泛型类型的变量分配方法引用?

[英]In Java is it possible to assign a method reference to a variable whose class has a generic type?

假设我们有以下课程:

interface Event {
}

@FunctionalInterface
interface EventListener<T extends Event> {
  void onEvent(T event);
}

class Service {

  class ServiceEvent implements Event {
  }

  public void onServiceEvent(ServiceEvent event) {
  }
}

为什么以下任务编译没有任何问题:

Service service = new Service();
EventListener<ServiceEvent> listener = service::onServiceEvent;

但是这一个:

Service service = new Service();
EventListener<? extends Event> anotherListener = service::onServiceEvent;

失败并出现此编译错误:

Error: java: incompatible types: invalid method reference incompatible types: Event cannot be converted to Service.ServiceEvent

public void onServiceEvent(ServiceEvent event) {}

这只接受ServiceEvent参数。 就像:

EventListener<ServiceEvent> listener = service::onServiceEvent;

但:

EventListener<? extends Event> anotherListener

不仅可以接受ServiceEvent ,还可以接受Event类型的所有子类型。 因此,类型不匹配

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM