将函数引用作为参数传递

时间:2016-10-27 21:41:08

标签: java lambda functional-programming java-8

是否可以将方法的引用作为参数传递?

例如:

public static void main(String[] args) {
    String data = "name: John, random text, address: leetStreet";
    Person person;

    //if regex matches, use method reference, to send the result. 
    applyDataToPerson(data, "name: (\\w+)", person, Person::setName);
    applyDataToPerson(data, "address: (\\w+)", person, Person::setAddress);
}

private static void applyDataToPerson(String data, String regex, Person person, 
 Function<Person> f) {
    Matcher match = Pattern.compile(regex).matcher(data);
    if (match.matches()) person.f(match.group(1));
}

class Person {
    private String name;
    private String address;

    public void setName(String name) {
        this.name = name;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

如果没有,那么提供方法参考的替代方法是什么?开关案例构造?

1 个答案:

答案 0 :(得分:5)

我认为您正在寻找BiConsumer

private static void applyDataToPerson(String data, String regex, Person person, BiConsumer<Person, String> action) {
    Matcher match = Pattern.compile(regex).matcher(data);
    if (match.matches()) action.accept(person, match.group(1));
}

或者,您可以缩短方法签名并使用捕获person引用的单个参数Consumer

public static void main(String[] args) {
    String data = "name: John, random text, address: leetStreet";
    Person person;

    //if regex matches, use method reference, to send the result. 
    applyData(data, "name: (\\w+)", person::setName);
    applyData(data, "address: (\\w+)", person::setAddress);
}

private static void applyData(String data, String regex, Consumer<String> action) {
    Matcher match = Pattern.compile(regex).matcher(data);
    if (match.matches()) action.accept(match.group(1));
}