将函数引用作为参数传递

贾斯珀

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

例如:

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;
    }
}

如果不是,那么提供引用方法的替代方法是什么?开关盒构造?

shmosel

我认为您正在寻找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));
}

另外,您可以缩短方法签名,并使用单个参数Consumer来捕获您的person引用:

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));
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

是否有将FXML控制器引用作为参数传递给方法的通用方法?

将方法引用作为参数传递

如何弱引用作为参数传递的函数

从std :: stringstream传递std :: string引用作为参数

将对基类的引用作为模板参数传递

将const unique_ptr引用作为参数传递

制作一个将函数调用作为参数传递给可传递函数的函数。

C ++ 11-将引用作为所有权的构造函数参数传递

Elixir将模块的引用作为函数参数传递

引用作为参数

将类类型作为函数参数传递并用作?上课

将引用作为参数传递给类的正确方法

将引用作为函数参数传递不起作用

为什么我不能传递引用作为std :: async的函数参数

是否可以将* this作为接受引用(&)的函数的参数传递?

在C ++中将模板类引用作为参数传递

如何将对子矩阵视图的持久引用作为函数参数传递?

将函数作为参数传递

作为参数传递时,在函数中更新指针地址。[将指针作为C中的引用传递]

如何在C#中将对STATIC方法的引用作为函数参数传递?

将对向量的引用作为参数传递

将类引用作为构造函数参数传递

引用作为字符串传递的参数

使用作为参数传递的函数声明

C++:将引用作为参数传递,但该函数不接受引用作为参数

如何创建一个将打印方法引用作为参数的函数?

如何将 ng-model 的引用作为函数的参数传递?

如何将泛型方法引用作为参数传递?

为什么不能将作为常量引用传递给函数的数组的 .size() 用作模板参数?