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

标签 java generics lambda java-8

有什么方法可以使用如下更通用的类型来引用 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/

相关文章:

java - JPA持久化单元写入文件?

Java 等同于 C# 中的 where

python - 在一行中使用一个表达式两次 - 作为字符串格式的条件和?

c# - LINQ 中的可迭代析取

c++ - std::functions 是否由 C++11 编译器内联?

java - 我可以在java中将Canvas导出为图像吗?

java - 如何使用java core实现JNDI机制?

Java:是否可以将 Class<?> 对象与泛型类型参数进行比较?

java泛型参数化类型

c++ - 各种类型的容器 - C++