gpt4 book ai didi

java - 分配给更通用类型的引用

转载 作者:行者123 更新时间:2023-11-30 06:45:38 27 4
gpt4 key购买 nike

有什么方法可以使用如下更通用的类型来引用此::方法吗?

Number method(Integer input){ return 1;}

void test(){
Function<Integer, Number> ref = this::method; //OK
Function<Number, Number> moreGenericRef = this::method // does not compile.
Function<? extends Number, Number> moreGenericRef2 = this::method // does not compile.
}

我希望能够执行以下操作。

Map<String, Function<Number,Number>> maps;
maps.add("method1", this::method)
maps.add("method2", this::method2)

maps.get("methods1").apply(1.2);
maps.get("methods2").apply(1);

这些函数是将由 Stream 的映射器调用的适配器

最佳答案

你需要函数的参数是逆变而不是协变:

Function<? super Integer, ? extends Number> moreGenericRef2 = this::method;

这可以很好地编译,并且还允许返回类型是 Number 的任何后代。

参见 PECS ,代表 Producer Extends,Consumer Super。另见 covariance and contravariance以获得对该主题的深入介绍。

关于java - 分配给更通用类型的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48630170/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com