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

时间:2017-08-05 11:38:08

标签: java generics

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

1 个答案:

答案 0 :(得分:1)

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