Java 8 链式方法参考? [英] Java 8 chained method reference?

查看:43
本文介绍了Java 8 链式方法参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个典型的 Java Bean:

Suppose there is a typical Java Bean:

class MyBean {
    void setA(String id) {
    }

    void setB(String id) { 
    }

    List<String> getList() {
    }
}

我想在 BiConsumer 的帮助下创建一种更抽象的调用 setter 的方法:

And I would like to create a more abstract way of calling the setters with the help of a BiConsumer:

Map<SomeEnum, BiConsumer<MyBean, String>> map = ...
map.put(SomeEnum.A, MyBean::setA);
map.put(SomeEnum.B, MyBean::setB);
map.put(SomeEnum.List, (myBean, id) -> myBean.getList().add(id));

有没有办法替换 lambda (myBean, id) ->myBean.getList().add(id) 带有链接的方法引用,例如 (myBean.getList())::addmyBean::getList::add 还是别的什么?

Is there a way to replace the lambda (myBean, id) -> myBean.getList().add(id) with a chained method reference, something like (myBean.getList())::add or myBean::getList::add or something else?

推荐答案

不,方法引用不支持链接.在您的示例中,不清楚这两种方法中的哪一种应该接收第二个参数.

No, method references do not support chaining. In your example it wouldn’t be clear which of the two methods ought to receive the second parameter.

但如果你坚持……

static <V,T,U> BiConsumer<V,U> filterFirstArg(BiConsumer<T,U> c, Function<V,T> f) {
    return (t,u)->c.accept(f.apply(t), u);
}

BiConsumer<MyBean, String> c = filterFirstArg(List::add, MyBean::getList);

该方法的命名建议将其视为采用现有的 BiConsumer(此处为 List.add)并添加一个函数(此处为 MyBean.getList()) 到它的第一个参数.很容易想象用于过滤第二个参数或同时过滤两个参数的等效实用方法会是什么样子.

The naming of the method suggest to view it as taking an existing BiConsumer (here, List.add) and prepend a function (here, MyBean.getList()) to its first argument. It’s easy to imagine how an equivalent utility method for filtering the second argument or both at once may look like.

然而,它主要用于将现有实现与另一个操作相结合.在您的具体示例中,使用站点并不比普通的 lambda 表达式好

However, it’s mainly useful for combining existing implementations with another operation. In your specific example, the use site is not better than the ordinary lambda expression

BiConsumer<MyBean, String> c = (myBean, id) -> myBean.getList().add(id);

这篇关于Java 8 链式方法参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆