Return method reference

后端 未结 2 1155
谎友^
谎友^ 2021-01-15 20:06

I am playing around in Java 8. How can I return a method reference?

I am able to return a lambda but not the method reference.

My attempts:

p         


        
相关标签:
2条回答
  • 2021-01-15 20:29

    You have a small mis-understanding of how method-references work.

    First of all, you cannot new a method-reference.

    Then, let's reason through what you want to do. You want the method forEachChild to be able to return something that would accept a List and a Consumer. The List would be on which object to invoke forEach on, and the Consumer would be the action to perform on each element of the list. For that, you can use a BiConsumer: this represents an operation taking 2 parameters and returning no results: the first parameter is a list and the second parameter is a consumer.

    As such, the following will work:

    public <T> BiConsumer<List<T>, Consumer<? super T>> forEachChild() {
        return List::forEach;
    }
    

    This type of method-reference is called "Reference to an instance method of an arbitrary object of a particular type". What happens is that the first parameter of type List<T> becomes the object on which forEach will be invoked, by giving it as parameter the Consumer.

    Then you can use it like:

    forEachChild().accept(Arrays.asList("1", "2"), System.out::println);
    
    0 讨论(0)
  • 2021-01-15 20:31

    I would like to add some points.

    You can't instantiate unbounded type instance.

    List<?> list = new ArrayList<?>();
    

    Second, as Tunaki mentioned, you can't make references to new MyObject::staticMethod when you make method references

    The other thing is, forEach(Consumer<T> consumer) (Terminal operation for pipeline streams) doesn't return anything. It only eats whatever we feed it.

    -Hope this may help :)

    0 讨论(0)
提交回复
热议问题