How can I create a list of method references?

大城市里の小女人 提交于 2019-12-07 08:07:18

问题


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

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?


回答1:


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

This code, for example, passes compilation :

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

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.

You can use a BiConsumer<TargetClass,String> :

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


来源:https://stackoverflow.com/questions/40383246/how-can-i-create-a-list-of-method-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!