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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With