Java 8 Feature Reference with Arguments

Trying to figure out how to reference instance functions. I figured out how to define getters, but setters give me problems. I am not sure how to write a function for a given method signature and a given base class.

Which type is Foo::setBarlower?

public class Foo {
    private String bar;

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }
}


{
    //Works great!
    Function<Foo, String> func1 = Foo::getBar;

    //Compile error ?
    Function<Foo, String> func2 = Foo::setBar;
    //Compile error ?
    Function<Foo, Void, String> func3 = Foo::setBar;
}
+4
source share
2 answers

Yours Function<Foo, String> func2 = Foo::setBar;is a compilation error, because public void setBar(String bar)it is not a function from Footo String, it is actually a function from Stringto Void.

If you want to send the installer as a reference to a method, you need BiConsumer, taking Fooand Stringhow

final BiConsumer<Foo, String> setter = Foo::setBar;

, Foo, Consumer,

Foo foo = new Foo();
final Consumer<String> setBar = foo::setBar;
+4

setBar void, void. "". BiConsumer, Foo :

BiConsumer<Foo, String> func2 = Foo::setBar;
+2

Source: https://habr.com/ru/post/1612742/


All Articles