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:
Bound
and Unbound
receiver method references?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.
Basically, unbound receivers allow you to use instance methods as if they were static methods with a first parameter of the declaring type - so you can use them as functions by passing in whatever instance you want. With a bound receiver, the "target" instance is effectively part of the function.
An example might make this clearer:
import java.util.function.*;
public class Test {
private final String name;
public Test(String name) {
this.name = name;
}
public static void main(String[] args) {
Test t1 = new Test("t1");
Test t2 = new Test("t2");
Supplier<String> supplier = t2::method;
Function<Test, String> function = Test::method;
// No need to say which instance to call it on -
// the supplier is bound to t2
System.out.println(supplier.get());
// The function is unbound, so you need to specify
// which instance to call it on
System.out.println(function.apply(t1));
System.out.println(function.apply(t2));
}
public String method() {
return name;
}
}
See more on this question at Stackoverflow