21

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?

5
  • What are you trying to achieve ? This is wrong - people.add(new Person(null));people.forEach(Person::setBornTrue); Commented Aug 24, 2014 at 5:14
  • people.add(new Person(null)); is this line right ? why null ? your code works for me but if you removed null. Commented Aug 24, 2014 at 5:14
  • Cut and paste error ... removed the null. Commented Aug 24, 2014 at 5:24
  • I am wondering why this is not possible as well. Commented Oct 28, 2018 at 0:53
  • Take a look at MethodHandle, but it so complicated, nothing like std::bind in C++ Commented Jan 30, 2020 at 9:58

1 Answer 1

27

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes ... while the answer above is how to set this without a method reference, is there no way to code this with a method reference?
@user465342 Updated with an alternative solution, which is not plain java, but uses a method reference.
Very impressive! Is there any reference you used to create that? Been looking for a good resource.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.