如何创建方法引用列表? [英] How can I create a list of method references?

查看:170
本文介绍了如何创建方法引用列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要处理一个列表,并为每个项目调用目标对象上的不同方法。看起来很优雅,我可以创建一个方法引用列表来执行此操作,因此对于列表中的每个索引,我可以调用与其对应的适当方法引用。

I have a need to work through a list and for each item call a different method on a target object. It seems elegant that I could just create a list of method references to do this, so for each index in the list, I could call the appropriate method reference that corresponds to it.

private final static List<Consumer<String>> METHODS = (List<Consumer<String>>) Arrays.asList(
     TargetClass::setValue1,
     TargetClass::setValue2,
     TargetClass::setValue3,
     TargetClass::setValue4,
     TargetClass::setValue5);

然而,Eclipse正在标记这些错误此表达式的目标类型必须是功能界面。现在,TargetClass这里是一个普通的类,而不是一个接口...这是否意味着没有办法完成我在这里尝试做的事情?

However, Eclipse is flagging these with the error The target type of this expression must be a functional interface. Now, TargetClass here is a regular class, not an interface ... does that mean there is no way to accomplish what I'm trying to do here?

推荐答案

您的方法引用可能与 Consumer< String> 功能界面不匹配。

It's possible your method references don't match the Consumer<String> functional interface.

此代码例如传递编译:

 private final static List<Consumer<String>> METHODS = Arrays.asList(
     Double::valueOf,
     Integer::valueOf,
     String::length);

由于您的方法似乎不是静态的,因此它们与 Consumer< String> ,因为这些方法有一个额外的隐式参数 - 该方法将应用于的实例。

Since your methods don't seem to be static, they don't match Consumer<String>, since these methods have an additional implicit parameter - the instance that the method would be applied on.

您可以使用a BiConsumer< TargetClass,String>

private final static List<BiConsumer<TargetClass,String>> METHODS = Arrays.asList(
     TargetClass::setValue1,
     TargetClass::setValue2,
     TargetClass::setValue3,
     TargetClass::setValue4,
     TargetClass::setValue5);

这篇关于如何创建方法引用列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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