Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method references with a parameter

Tags:

In Java 8, with the following class

 class Person {

    private boolean born;

    Person() {
    }

    public void setBornTrue() {
        born = true;
    }

    public void setBorn(boolean state) {
        born = state;
    }

  }

it is possible to call the setBornTrue method via a method reference:

    ArrayList<Person> people = new ArrayList<>();
    people.add(new Person());

    people.forEach(Person::setBornTrue);

but how would I use the forEach method and use the setBorn using a method reference? Trying:

    people.forEach(Person::setBorn);

results in an error, "Cannot resolve method setBorn".

In addition, how would I pass in the value of True?

like image 491
user465342 Avatar asked Aug 24 '14 05:08

user465342


People also ask

How do you pass parameters in a method reference in Java?

In this case, instead of using a specific object, you can use the name of the class. Therefore, the first parameter of the functional interface matches the invoking object. This is why we call it the parameter method reference. Rest parameters match the parameters (if any) that are specified by the method.

What are three ways for method reference?

Types of Method ReferencesStatic Method Reference. Instance Method Reference of a particular object. Instance Method Reference of an arbitrary object of a particular type. Constructor Reference.

What is a method reference?

Method references are a special type of lambda expressions. They're often used to create simple lambda expressions by referencing existing methods. There are four kinds of method references: Static methods. Instance methods of particular objects. Instance methods of an arbitrary object of a particular type.


1 Answers

With lambda:

people.forEach((p) -> p.setBorn(true));

Found no other ways only using the java 8 API.


With this custom function:

public static <T, U> Consumer<T> bind2(BiConsumer<? super T, U> c, U arg2) {
    return (arg1) -> c.accept(arg1, arg2);
}

You can do:

people.forEach(bind2(Person::setBorn, true));

If this kind of utility methods is available in the java API or in a library, please let us know.

like image 53
Volune Avatar answered Oct 16 '22 15:10

Volune