-->

Return method reference

2020-03-30 06:20发布

问题:

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:

public Supplier<?> forEachChild(){
     return new ArrayList<?>::forEach;
}

OR

public Function<?> forEachChild(){
     return new ArrayList<?>::forEach;
}

回答1:

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


回答2:

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