Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a list of method references?

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?

like image 556
Steve Avatar asked Nov 02 '16 15:11

Steve


1 Answers

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);
like image 107
Eran Avatar answered Oct 18 '22 17:10

Eran