I have following piece of code
StringJoiner joiner = new StringJoiner(", ");
joiner.add("Something");
Function<StringJoiner,Integer> lengthFunc = StringJoiner::length;
Function<CharSequence,StringJoiner> addFunc = StringJoiner::add;
Last line cause an error
Error:(54, 53) java: invalid method reference
non-static method add(java.lang.CharSequence) cannot be referenced from a static context
I understand that this method can't be used in static way and I should have something like :
Function<CharSequence,StringJoiner> addFunc = joiner::add;
instead. However I can't understand why third line, with StringJoiner::length;
is for java compiler perfectly correct. Can someboedy explain me why is that ?
In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.
A static method reference refers to a static method in a specific class. Its syntax is className::staticMethodName , where className identifies the class and staticMethodName identifies the static method. An example is Integer::bitCount .
The static keyword in Java is a modifier that makes a member of a class independent of the instances of that class. In other words, the static modifier is used to define variables and methods related to the class as a whole, rather than to an instance (object) of the class.
Java provides a new feature called method reference in Java 8. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.
Function<StringJoiner,Integer> lengthFunc = StringJoiner::length;
lengthFunc
is a Function that takes a StringJoiner
and returns an Integer
. Therefore any instance method of StringJoiner
that takes nothing and returns an Integer
matches this interface. The instance of which the method is called will be the StringJoiner
required by the Function<StringJoiner,Integer>
.
On the other hand in
Function<CharSequence,StringJoiner> addFunc = StringJoiner::add
addFunc
is a Function
that takes a CharSequence
and returns StringJoiner
. No instance method of StringJoiner
matches this interface, since the function doesn't have an input StringJoiner
instance to apply the add
method on.
You would need a BiFunction
to match the signature of StringJoiner::add
:
BiFunction<StringJoiner,CharSequence,StringJoiner> addFunc = StringJoiner::add;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With