Java 8:方法引用Bound Receiver和UnBound Receiver之间的区别 [英] 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.
- 静态方法参考。
- 实例方法(绑定接收器)。
- 实例方法(UnBound接收器)。
- 构造函数引用。
- Static method reference.
- Instance Method (Bound receiver).
- Instance Method (UnBound receiver).
- Constructor reference.
随附静态方法引用
和构造函数引用
我没有问题,但实例方法(绑定接收器)
和实例方法(UnBound接收器)
让我很困惑。在 Bound
接收器中,我们使用Object引用变量来调用如下方法:
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
和未绑定
接收方法引用? - 我们应该在哪里使用
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?
I also found the explanation of Bound
and Unbound
receiver from Java 8 language features books, but was still confused with the actual concept.
推荐答案
unBound接收器的想法,例如 String :: length
是你指的是对象的
方法,将作为lambda 的一个参数提供。例如,
lambda表达式(String s) - > s.toUpperCase()
可以重写为 String :: toUpperCase
。
The idea of unBound receiver such as String::length
is that you’re referring to a
method to an object that will be supplied as one of the parameters of the lambda. For example,
the lambda expression (String s) -> s.toUpperCase()
can be rewritten as String::toUpperCase
.
但是Bounded指的是当您将
lambda中的方法调用已存在的外部对象时的情况。例如,lambda表达式() - >
可以重写为
expensiveTransaction.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
(arg0,rest) - > arg0.instanceMethod(rest)
可以是 ClassName :: instanceMethod
( arg0
的类型为 ClassName
)
(args) - > expr.instanceMethod(args)
可以是 expr :: instanceMethod
在Action Book
Answer retired from Java 8 in Action book
这篇关于Java 8:方法引用Bound Receiver和UnBound Receiver之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!