Java Reference
In-Depth Information
This statement uses a lambda expression that represents a function that takes no argument and returns an
int
. The body of the expression uses a
String
object called
"Ellen"
to invoke the
length()
instance method of the
String
class. You can rewrite this statement using an instance method reference with the
"Ellen"
object as the bound
receiver using a
Supplier<Integer>
as the target type as shown:
Supplier<Integer> supplier =
"Ellen"::length
;
System.out.println(supplier.get());
5
Consider the following snippet of code to represent a
Consumer<String>
that takes a
String
as an argument and
returns
void
:
Consumer<String> consumer =
str -> System.out.println(str);
consumer.accept("Hello");
Hello
This lambda expression invokes the
println()
method on the
System.out
object. This can be rewritten using a
method reference with
System.out
as the bound receiver, as shown:
Consumer<String> consumer =
System.out::println
;
consumer.accept("Hello");
Hello
When the method reference
System.out::println
is used, the compiler looks at its target type, which is
Consumer<String>
that represents a function type that takes a
String
as an argument and returns
void
. The compiler
finds a
println(String)
method in the
PrintStream
class of the
System.out
object and uses that method for the
method reference.
As the last example in this category, you will use the method reference
System.out::println
to print the list of
persons, as shown:
List<Person> list = Person.getPersons();
FunctionUtil.forEach(list,
System.out::println
);
John Jacobs, MALE, 1975-01-20
Wally Inman, MALE, 1965-09-12
Donna Jacobs, FEMALE, 1970-09-12
Unbound Receiver
For an unbound receiver, use the
ClassName::instanceMethod
syntax. Consider the following statement in which the
lambda expression takes a
Person
as an argument and returns a
String
:
Function<Person, String> fNameFunc =
(Person p) -> p.getFirstName()
;