String.concat 用作双函数

String.concat used as a BiFunction

在尝试使用方法引用时,遇到了可以将 concat 方法用作 BiFunction 的情况,据我了解,BiFunction apply 方法需要 2 个输入参数并产生一个结果。而 concat 方法采用 1 个输入参数和 returns 具有此值的连接字符串。

示例代码:

public class Test {
  public static void main(String[] args) {
    Test t = new Test();
    String str1 = "Hello";
    String str2 = "Workld";
    System.out.println(t.stringManipulator(str1, str2, String::concat));
    System.out.println(str1);
    System.out.println(str2);
  }
  private String stringManipulator(String inputStr, String inputStr2, BiFunction<String, String, String> function) {
    return function.apply(inputStr, inputStr2);
  }
}

输出

HelloWorkld
Hello
Workld

有人可以帮助我了解这里发生了什么吗?

String.concat() 方法有两个参数。第一个是(隐式)参数是调用该方法的字符串,第二个是显式参数。

str1.concat(str2)

str1 是隐式参数(在 concat 方法中可以作为 this 访问),str2 是显式参数。

或者,如 Java 语言规范中所述 (https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.13.3)

If the form is ReferenceType :: [TypeArguments] Identifier, the body of the invocation method similarly has the effect of a method invocation expression for a compile-time declaration which is the compile-time declaration of the method reference expression. Run-time evaluation of the method invocation expression is as specified in §15.12.4.3, §15.12.4.4, and §15.12.4.5, where:

  • The invocation mode is derived from the compile-time declaration as specified in §15.12.3.

  • If the compile-time declaration is an instance method, then the target reference is the first formal parameter of the invocation method. Otherwise, there is no target reference.

  • If the compile-time declaration is an instance method, then the arguments to the method invocation expression (if any) are the second and subsequent formal parameters of the invocation method. Otherwise, the arguments to the method invocation expression are the formal parameters of the invocation method.

也就是说,

  BiFunction<String, String, String> function = String::concat;
  function.apply("abc", "def");

将被执行为

  "abc".concat("def");

The method reference String::concat represents an instance method reference for a target type whose function takes two String arguements and returns a String. The first arguement will be the receiver of the concat() method and the second arguement will be passed to the concat() method.

有关 未绑定接收器 的更多详细信息,请参阅 Beginning Java8 book。它有确切的例子解释。