[英]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.