I am trying to use Java 8 method references in my code. There are four types of method references available.
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:
I also found the explanation of bound and unbound receiver from Java 8 language features books, but was still confused with the actual concept.
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