Java Reference
In-Depth Information
This statement can be rewritten using the instance method reference, as shown:
Function<Person, String> fNameFunc = Person::getFirstName ;
In the beginning, this is confusing for two reasons:
The syntax is the same as the syntax for a method reference to a static method.
It raises a question: which object is the receiver of the instance method invocation?
The first confusion can be cleared by looking at the method name and checking whether it is a static or instance
method. If the method is an instance method, the method reference represents an instance method reference.
The second confusion can be cleared by keeping a rule in mind that the first argument to the function
represented by the target type is the receiver of the method invocation. Consider an instance method reference called
String::length that uses an unbound receiver. The receiver is supplied as the first argument to the apply() method,
as shown:
Function<String, Integer> strLengthFunc = String::length;
String name ="Ellen";
// name is the receiver of String::length
int len = strLengthFunc.apply(name);
System.out.println("name = " + name + ", length = " + len);
name = Ellen, length = 5
The instance method concat() of the String class has the following declaration:
String concat(String str)
The method reference String::concat represents an instance method reference for a target type whose function
takes two String arguments and returns a String . The first argument will be the receiver of the concat() method and
the second argument will be passed to the concat() method. The following snippet of code shows an example:
String greeting = "Hello";
String name = " Laynie";
// Uses a lambda expression
BiFunction<String, String, String> func1 = (s1, s2) -> s1.concat(s2);
System.out.println(func1.apply(greeting, name));
// Uses an instance method reference on an unbound receiver
BiFunction<String, String, String> func2 = String::concat;
System.out.println(func2.apply(greeting, name));
Hello Laynie
Hello Laynie
Search WWH ::




Custom Search