简体   繁体   中英

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. 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. Hence, the type mismatch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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