返回方法参考 [英] Return method reference

查看:135
本文介绍了返回方法参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java 8.如何返回方法引用?

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

我能够返回lambda而不是方法引用。

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

我的尝试:

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

OR

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


推荐答案

你有一个小错误 - 了解方法参考的工作原理。

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

首先,你不能方法参考。

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

然后,让我们通过理由你想做什么。您希望方法 forEachChild 能够返回接受 List 的内容消费者 List 将在哪个对象上调用 forEach on,以及 Consumer 将是对列表的每个元素执行的操作。为此,您可以使用 BiConsumer :这表示采用2个参数并且不返回结果的操作:第一个参数是列表,第二个参数是消费者。

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

此类方法引用称为引用实例方法特定类型的任意对象。会发生的是,类型 List< T> 的第一个参数将成为将调用 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.

然后你就可以使用它:

forEachChild().accept(Arrays.asList("1", "2"), System.out::println);

这篇关于返回方法参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆