简体   繁体   English

Java 8链式方法参考?

[英]Java 8 chained method reference?

Suppose there is a typical Java Bean: 假设有一个典型的Java Bean:

class MyBean {
    void setA(String id) {
    }

    void setB(String id) { 
    }

    List<String> getList() {
    }
}

And I would like to create a more abstract way of calling the setters with the help of a BiConsumer: 我想在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));

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? 有没有办法用链接的方法引用替换lambda (myBean, id) -> myBean.getList().add(id) ,类似(myBean.getList())::addmyBean::getList::add还是其他?

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

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. 该方法的命名建议将其视为采用现有的BiConsumer (在此为List.add ),并在其第一个参数前添加一个函数(在此为MyBean.getList() )。 It's easy to imagine how an equivalent utility method for filtering the second argument or both at once may look like. 容易想象一下,用于过滤第二个参数或同时过滤两个参数的等效实用程序的外观会是什么样子。

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 在您的特定示例中,使用网站并不比普通的lambda表达式更好。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM