Java 8 method reference: how to determine which method to take?

  • A+
Category:Languages

Lets say we have the following class:

public class NameCreator {      public String createName(String lastname) {         return lastname;     }      public String createName(String lastname, String firstName) {         return lastname + " " + firstname     }      ... } 

If I want to call it via Java 8 method reference:

NameCreator::createName 

I will get the error:

Cannot resolve method createName 

How can I define which of those methods I want to be called?

 


NameCreator::createName implies that either the method is static (kind #1 in the table below), or that the functional interface target also takes an instance of the class (kind #3, for example
BiFunction<NameCreator, String, String>). Your methods are not static, and so presumably your target does not take an instance, which is why you get the "Cannot resolve method" error. You probably want to use the method reference on an instance (kind #2). From within the class, you can use:

Function<String, String> func = this::createName 

From outside the class you can use:

NameCreator creator = new NameCreator(); Function<String, String> func = creator::createName; 

As to whether the one- or two-parameter version is used, it depends on what functional interface is being targeted. The above will use your first method, because Function<String, String> takes a String and returns a String. The following functional interface, as an example, would use your second method:

NameCreator creator = new NameCreator(); BiFunction<String, String, String> func = creator::createName; 

See: Function, BiFunction, and the whole java.util.function package

You may also be interested in the Java tutorial on method references, specifically this part:


There are four kinds of method references:

Kind                                                   | Example ============================================================================================== Reference to a static method                           | ContainingClass::staticMethodName -------------------------------------------------------+-------------------------------------- Reference to an instance method of a particular object | containingObject::instanceMethodName -------------------------------------------------------+-------------------------------------- Reference to an instance method of an arbitrary object | ContainingType::methodName of a particular type                                   | -------------------------------------------------------+-------------------------------------- Reference to a constructor                             | ClassName::new ============================================================================================== 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: