有什么方法可以使用如下更通用的类型来引用 this::method 吗?
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 ,代表生产者扩展,消费者 super 。另请参阅covariance and contravariance深入介绍该主题。
关于java - 分配给更通用类型的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48630170/