I have a function functionAcceptsMethod
which accepts a runnable method as a parameter, I want to call functionAcceptsMethod
by passing a method with parameters.
when I call functionAcceptsMethod
by passing without parameters its fine but how to pass a function with parameters.
here is an example
private void testFun() {
functionAcceptsMethod(this::funWithoutParams);
functionAcceptsMethod(this::funWithParams); // this where I need to pass params
//functionAcceptsMethod(() -> funWithParams("abcd")); // I tried this, is this the right
//way?
}
private void funWithoutParams() {
//do something
}
private void funWithParams(String testString) {
//do something
}
private void functionAcceptsMethod(Runnable method) {
method.run();
}
The right way is to have a version of your functionAcceptsMethod
method with the parameter:
private void <T> functionAcceptsMethod(Consumer<T> method, T argument) {
method.accept(argument);
}
Note that Runnable#run
is a functional interface without a parameter, so you cannot use it here. You have to use Consumer
. Now you can do this:
functionAcceptsMethod(this::funWithParams, "abc");
Check out java.util.function
for more possibilities.
Yes, The approach
functionAcceptsMethod(() -> funWithParams("abcd"));
is ok, if your purpose is to just pass method reference and get args in parameters of functionAcceptsMethod
method then use Consumer<T>
as function receiver argument
As you wanted an example:
public static <T> void functionAcceptsMethod(Consumer<T> consumer, T t){
consumer.accept(t);
}
This is a generic version and will accept any method that has single input parameter. and an example of usage:
public void example(){
// Automatic type inferring
functionAcceptsMethod(this::func, "f");
functionAcceptsMethod(this::func2, 0);
// Explicit type specification
functionAcceptsMethod<Float>(this::func3, 0f);
}
public void func(String s){
System.out.println(s);
}
public void func2(int i){
System.out.println(i);
}
public void func3(float f){
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.