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

查看:544
本文介绍了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()):: add myBean :: 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.

但是如果你坚持...

But if you insist on it…

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天全站免登陆