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

java 8 method reference with parameters
method reference in java 8 geeksforgeeks
java 8 pass method as parameter
method reference java 8 example mkyong
java method reference with multiple parameters
java method reference constructor
java 8 methods
java pass method as parameter

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
==============================================================================================

Java 8 Method Reference, What is the advantage of method reference in Java 8? 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:

Method references rely on inference. So without proper context from which the compiler can infer the target functional interface, that resolution error is raised.

You should assign it to an interface type that declares a method matching the signature (or use it in a context where the target type is defined, such as a method argument).

For example:

interface INameCreator {
    String create(String name);
}

interface INamesCreator {
    String create(String firstName, String lastName);
}

And then you can use the method references:

//match NameCreator.createName(String)
INameCreator creator = this::createName //within the class
INameCreator creator = nameCreatorInstance::createName 

And

//match NameCreator.createName(String, String)
INamesCreator creator = this::createName //within the class
INamesCreator creator = nameCreatorInstance::createName

If the method were static, you would be able to use the NameCreator::createName syntax in the same context.

Java 8 Method Reference: How to Use it, The Java Tutorials have been written for JDK 8. See JDK Release Notes for information about new features, enhancements, and removed or deprecated Method references enable you to do this; they are compact, easy-to-read lambda​  Java 8 - Method References - Method references help to point to methods by their names. A method reference is described using :: symbol. A method reference can be used to point the follow

If you want to create instances of type NameCreatorbased on Strings, use this:

 public static class NameCreator {

    public static String createName(String lastname) {
        return lastname;
    }

    public static String createName(String lastname, String firstName) {
        return lastname + " " + firstName;
    }
}

and then make calls like:

  List<String> items = new ArrayList<>();
    //
    items.forEach(NameCreator::createName);//uses the first method
    Map<String, String> map = new HashMap<>();
    //
    map.forEach(NameCreator::createName); //uses the second method

How to Convert a Lambda Expression to Method Reference in Java 8?, Time to understand Java 8 method reference and how to actually use it. If we only use a method of an object in another method, we still have to pass the We know that we can use lambda expressions instead of using an  jpanel – Java JScrollpane with background set as setBackground(new Color(0,0,0,122)); glitch-Exceptionshub February 25, 2020 Java Leave a comment Questions: Hi I have a JScrollPane on top of a JPanel in which that JPanel is on a JTabbedPane as shown in the image below that is fine when I first enter into the Dashboard Tab and don’t scroll

What is Method References in Java 8? An Example, A quick and practical overview of method references in Java. One of the most welcome changes in Java 8 was the introduction of lambda by frame size, but we'd need to specify two bikes for comparison: ? Instead, we can use a method reference to have the compiler handle parameter passing for us:. 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.

Method References (The Java™ Tutorials > Learning the Java , Method References allow us to shorten Lambda Expressions further down into useful feature added to Java 8, are method references, which make Lambda do is define a new Comparator for these objects while calling the .sort() method: As I spend a lot of time using Java 8 I thought that it might be useful to a series article of the new features in JDK8. In this article, we will be looking at Method References. What are Method References? It is a feature which is related to Lambda Expression. It allows us to reference constructors or methods without executing them.

Method References in Java, You can find the full example on GitHub. java 8 ,method references ,lambda ,​java 8 lambda expressions ,java ,tutorial ,objects ,instance method ,static method public Mono<Person> get(@PathVariable("id") long id) {. 34. The method reference myComparisonProvider::compareByName invokes the method compareByName that is part of the object myComparisonProvider. The JRE infers the method type arguments, which in this case are (Person, Person). Reference to an Instance Method of an Arbitrary Object of a Particular Type

Comments
  • Can you add the part of code in which you are calling that method? It would be useful for helping you.
  • Perfect. So what I can do is: Consumer<String> consumer = creator::createName. Or Function<String, String> consumer = ... and so on. Thank you.
  • Yep. If you don't care about the resulting strings, you can use Consumer or BiConsumer, depending on which method you want. Parameter lists always need to match exactly, but return types can also be ignored. (see my answer here)
  • You can reference instance methods with NameCreator::createName too, they don't have to be static. It just means that they take an extra first argument which represents the instance. e.g. BiFunction<NameCreator, String, String> func = NameCreator::createName; would reference the first method.
  • @JornVernee True, it was an oversimplification. Thanks, I've updated my answer. Hopefully its more comprehensive now.
  • what about static methods ?