Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

lambda - Java 8: Difference between method reference Bound Receiver and UnBound Receiver

I am trying to use Java 8 method references in my code. There are four types of method references available.

  1. Static method reference.
  2. Instance Method (Bound receiver).
  3. Instance Method (UnBound receiver).
  4. Constructor reference.

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

In UnBound receiver we are using Class name for calling a method like:

ClassName::Instance Method.

I have the following question:

  1. What is the need for different types of method references for Instance Methods?
  2. What is the difference between Bound and Unbound receiver method references?
  3. Where should we use Bound receiver and where should we use Unbound 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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) can be ClassName::staticMethod // This is static (you can think as unBound also)

(arg0, rest) -> arg0.instanceMethod(rest) can be ClassName::instanceMethod (arg0 is of type ClassName) // This is unBound

(args) -> expr.instanceMethod(args) can be expr::instanceMethod // This is Bound

Answer retrieved from Java 8 in Action book


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...