简体   繁体   English

如何将方法引用传递给协变参数

[英]How to pass a method reference to a covariant parameter

Given we have the following classes an methods:鉴于我们有以下类和方法:

class Fruit {}
class Orange extends Fruit {}

void process(Consumer<? extends Fruit> action) {}
void eatOnlyOranges(Orange evt) {}

This compiles without warning.这会在没有警告的情况下编译。

    Consumer<Orange> consumer = this::eatOnlyOranges;
    process(consumer);

I want to allow this, but it doesn't compile?我想允许这个,但它不能编译?

    process(this::eatOnlyOranges);

Can I change the signature of process(Consumer<? extends Fruit> action) to make it work?我可以更改process(Consumer<? extends Fruit> action)的签名以使其工作吗?

NOTE: Please assume that the implementation of process(..) will check if the given Consumer can handle the given Fruit .注意:请假设process(..)的实现将检查给定的Consumer可以处理给定的Fruit This detail is not relevant for this question.这个细节与这个问题无关。

Besides @EmersonCod's answer, changing the method signature to除了@EmersonCod 的回答,将方法签名更改为

<T extends Fruit> void process(Consumer< T > action) {
    // ...
}

seems to do the job.似乎做的工作。

您需要将Consumer转换为特定类型

process((Consumer<Orange>) this::eatOnlyOranges)

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

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