java - 为什么方法引用与具有不同参数数量的功能接口(interface)兼容?

标签 java java-8 method-reference functional-interface

我知道,如果引用的方法采用与功能接口(interface)相同数量的参数并返回相同的类型,则方法引用可用于实现功能接口(interface),但为什么在某些情况下引用的方法的参数数量与函数接口(interface)的参数数量不同功能接口(interface)但仍然兼容?

我有一个简单的 BiConsumer,我尝试使用方法引用来实现它。我知道只要参数数量匹配,我也可以使用 lambda 表达式。我将展示代码以清楚地解释它。

我有一个BiConsumer<ArrayList<String>, ? super String>我想实现。

Lambda 表达式的实现方法是:

BiConsumer<ArrayList<String>, ? super String> b = (firstArg,secondArg) -> firstArg.add(secondArg);因为它们都需要 2 个输入参数,所以没有问题。

但是为什么BiConsumer<ArrayList<String>, ? super String> a = ArrayList::add;还兼容吗? add ArrayList 上的方法只需要 1 个输入参数,但功能接口(interface)需要 2 个。

任何答案将不胜感激。谢谢!

最佳答案

15.12.2.1. Identify Potentially Applicable Methods

A method reference expression (§15.13) is potentially compatible with a functional interface type T if, where the arity of the function type of T is n, there exists at least one potentially applicable method when the method reference expression targets the function type with arity n (§15.13.1), and one of the following is true:

  • The method reference expression has the form ReferenceType :: [TypeArguments] Identifier and at least one potentially applicable method is either (i) static and supports arity n, or (ii) not static and supports arity n-1.

您要使用的函数类型的参数为 2

void accept(T t, U u);

并且 ArrayList::add 引用的方法的数量为 1,并且它不是静态的。这使得它具有潜在的适用性。

关于java - 为什么方法引用与具有不同参数数量的功能接口(interface)兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57828856/

相关文章:

java - Jackson - 获取数组内的条目

java - Mahout 中的 IllegalArgumentException

java - WebView loadDataWithbaseURL java.lang.NullPointerException

java - 将默认项添加到流集合

java.lang.UnsatisfiedLinkError : "no swt-win32-4623" running Visualization Customizer

java - 什么 Java 库对象封装了数字和 `TimeUnit`?

java - 创建将调用父类(super class)方法的非捕获方法引用

java - 内联所选方法引用的调用方法

Java 日志记录说明

java - 为什么 Java 8 中的 lambda 表达式要求其内部使用的变量使用 "final"修饰符,但在使用方法引用时却不需要?