Java 8 chained method reference?

前端 未结 1 577
悲哀的现实
悲哀的现实 2020-11-27 07:13

Suppose there is a typical Java Bean:

class MyBean {
    void setA(String id) {
    }

    void setB(String id) { 
    }

    List getList() {
         


        
相关标签:
1条回答
  • 2020-11-27 07:36

    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. 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

    BiConsumer<MyBean, String> c = (myBean, id) -> myBean.getList().add(id);
    
    0 讨论(0)
提交回复
热议问题