Java 8:方法引用绑定接收器和未绑定接收器的区别 [英] Java 8: Difference between method reference Bound Receiver and UnBound Receiver
问题描述
我正在尝试在我的代码中使用 Java 8 方法引用.有四种类型的方法引用可用.
I am trying to use Java 8 method references in my code. There are four types of method references available.
- 静态方法参考.
- 实例方法(绑定接收器).
- 实例方法(未绑定接收器).
- 构造函数参考.
使用 Static method reference
和 Constructor reference
我没有问题,但是 Instance Method (Bound receiver)
和 Instance Method (未绑定的接收器)
真的让我很困惑.在 Bound
接收器中,我们使用对象引用变量来调用如下方法:
With Static method reference
and Constructor reference
i have no problem, but Instance Method (Bound receiver)
and Instance Method (UnBound receiver)
really confused me. In Bound
receiver, we are using an Object reference variable for calling a method like:
objectRef::Instance Method
在 UnBound
接收器中,我们使用类名来调用如下方法:
In UnBound
receiver we are using Class name for calling a method like:
ClassName::Instance Method.
我有以下问题:
- 不同类型的实例方法需要什么方法引用?
Bound
和Unbound
接收器方法引用有什么区别?- 我们应该在哪里使用
Bound
接收器,我们应该在哪里使用Unbound
接收器?
- What is the need for different types of method references for Instance Methods?
- What is the difference between
Bound
andUnbound
receiver method references? - Where should we use
Bound
receiver and where should we useUnbound
receiver?
我还从 Java 8 语言特性书籍,但仍然与实际概念混淆.
I also found the explanation of Bound
and Unbound
receiver from Java 8 language features books, but was still confused with the actual concept.
推荐答案
像 String::length
这样的 unBound 接收器的想法是你指的是将作为 lambda 参数之一提供的对象的方法.例如,lambda 表达式 (String s) ->s.toUpperCase()
可以改写为 String::toUpperCase
.
The idea of the unBound receiver such as String::length
is you're referring to a
method of an object that will be supplied as one of the lambda's parameters. For example,
the lambda expression (String s) -> s.toUpperCase()
can be rewritten as String::toUpperCase
.
但是有界是指当你在一个方法中调用一个方法时的情况lambda 到一个已经存在的外部对象.例如,lambda 表达式 () ->priceTransaction.getValue()
可以改写为 expensiveTransaction::getValue
.
But Bounded refers to a situation when you’re calling a method in a
lambda to an external object that already exists. For example, the lambda expression () -> expensiveTransaction.getValue()
can be rewritten as expensiveTransaction::getValue
.
三种不同的方法引用方式的情况
Situations for three different ways of method reference
(args) ->ClassName.staticMethod(args)
可以是 ClassName::staticMethod
//这是静态的(你也可以认为是 unBound)
(args) -> ClassName.staticMethod(args)
can be ClassName::staticMethod
// This is static (you can think as unBound also)
(arg0, rest) ->arg0.instanceMethod(rest)
可以是 ClassName::instanceMethod
(arg0
is of type ClassName
)//这是未绑定的
(arg0, rest) -> arg0.instanceMethod(rest)
can be ClassName::instanceMethod
(arg0
is of type ClassName
) // This is unBound
(args) ->expr.instanceMethod(args)
可以是 expr::instanceMethod
//这是绑定的
(args) -> expr.instanceMethod(args)
can be expr::instanceMethod
// This is Bound
从Java 8 in Action 书中检索的答案
这篇关于Java 8:方法引用绑定接收器和未绑定接收器的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!