Return method reference

后端 未结 2 1193
谎友^
谎友^ 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  BiConsumer, Consumer> 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 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);
    

提交回复
热议问题