I want to generify method reference to trigger methods per type,
I save Map of Function Interfaces by key, the functions will call services method, but I have an issue that I can't define paramater using method reference, e.g.:
private Map<Type, Function<User, Boolean>> functionInterfaces = new HashMap<>();
{
functionInterfaces.put(Type.MY_TYPE1, MyService::myTypeMethod1);
functionInterfaces.put(Type.MY_TYPE2, MyService::myTypeMethod2);
functionInterfaces.put(Type.MY_TYPE3, MyService::myTypeMethod3);
}
Currently I need to create method per type
private boolean myTypeMethod1(Parameters parameters) {
return myGenericTypeMethod(parameters, Type.MY_TYPE1);
}
private boolean myTypeMethod2(Parameters parameters) {
return myGenericTypeMethod(parameters, Type.MY_TYPE2);
}
I call function using apply:
if (map.containsKey(key)) {
map.get(key).apply(new Parameters.Builder().build());
}
Can I refactor code to use single method?
The problem with this
functionInterfaces.put(Type.MY_TYPE1, MyService::myTypeMethod1);
is that MyService::myTypeMethod1
is an instance method. It must take a MyService
, because that is the instance to be acted upon. You are trying assign it to Function<User, Boolean>
, but where is the instance in this case?
I don't know whether it makes sense to because we don't have much context, but changing the declaration to
Map<Type, BiFunction<MyService, Parameters, Boolean>> functionInterfaces = ...
would at least solve the compiler's problem.
In this case, it acts upon MyService
, takes a Parameter
and returns a Boolean
.
Alternatively - and, again, we have limited context - making the MyService
methods static would be sufficient, but you can only do that if they don't require any state.
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