[英]How does method references work under hood when there are multiple arguments
How does compiler ensure that equivalent lambda for below statement编译器如何确保以下语句的等效 lambda
BinaryOperator<String> concatOperator = String::concat;
is是
BinaryOperator<String> concatOperator = (resultString, inputString) -> resultString.concat(inputString);
and not并不是
BinaryOperator<String> concatOperator = (resultString, inputString) -> inputString.concat(resultString);
This behaviour is well-documented in the JLS这种行为在 JLS 中有详细记录
15.13.3.
15.13.3. Run-Time Evaluation of Method References
方法参考的运行时评估
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 .
如果编译时声明是实例方法,则方法调用表达式(如果有)的 arguments 是调用方法的第二个和后续形参。 Otherwise, the arguments to the method invocation expression are the formal parameters of the invocation method.
否则,方法调用表达式的 arguments 是调用方法的形参。
and it seems reasonable and intuitive.它似乎合理且直观。 If you take a method with arity
n
( n > 2
), it becomes obvious that the target reference should be the first parameter, not the last, not the one in the middle.如果您采用具有
n
( n > 2
) 的方法,很明显目标引用应该是第一个参数,而不是最后一个,而不是中间的那个。
The line of code using method references is categorized under the types of method reference as -使用方法引用的代码行在方法引用的 类型下分类为 -
Reference to an Instance Method of an Arbitrary Object of a Particular Type参考特定类型的任意Object的实例方法
where the first lambda argument is inferred as an object of type String
on which the method named concat
is invoked with the parameter value equivalent to the second lambda argument.其中,第一个 lambda 参数被推断为
String
类型的 object,在其上调用名为concat
的方法,其参数值等效于第二个 lambda 参数。 In the above case as:在上述情况下:
BinaryOperator<String> concatOperator = (result, input) -> result.concat(input);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.