I want to pass method as a parameter in a method like
callMethod(someArg, methodToPass)
And in the definition of callMethod, I want to call this fn ie. MethodToPass i.e in another java file and the arguments for fn MethodToPass are being initialized in this callMethod only.
Please tell me how can I do that??
2 Answers 2
It depends on the signature of your "methodToPass".
For example, if your method accepts a single argument and has a return type, you can use Function<X,Y>:
public static <X,Y> Y callMethod (X arg, Function<X,Y> func) {
return func.apply(arg);
}
and call it with:
Integer result = callMethod ("abc", String::length);
If your method has a signature that doesn't match predefined functional interfaces, you can create a custom interface.
Either generic:
public interface MyFunc<T1,T2,T3,T4,T5>
{
public void apply (T1 t1, T2 t2, T3 t3, T4 t4, T5 t5);
}
or not:
public interface MyFunc
{
public void apply (Type1 t1, Type2 t2, Type3 t3, Type4 t4, Type5 t5);
}
where TypeN represent actual classes.
Now, callMethod becomes (in the non-generic version):
public static void callMethod (MyFunc method) {
Type1 a1 = ...
Type2 a2 = ...
Type3 a3 = ...
Type4 a4 = ...
Type5 a5 = ...
method.apply(a1,a2,a3,a4,a5);
}
And you call it with:
callMethod (SomeClass::methodToPass);
Where methodToPass is defined as:
static void methodToPass (Type1 t1, Type2 t2, Type3 t3, Type4 t4, Type5 t5) {
...
}
3 Comments
SomeClass can also be an instance if you want to call a non-static method and it can also be this if you want to reference the current instance.You can declare a @FunctionalInterface containing the method (although chances are the JDK already provides one).
@FunctionalInterface
interface MethodToPass {
void methodToCall(int someArg);
}
Then, you can pass the method as a reference:
class YourClass {
// note same signature as the inferface method
public void methodToPass(iont arg) {
System.out.println("called with " + arg);
}
}
class OtherClass {
public static void main(String[] args) {
YourClass c = new YourClass();
callMethod(c::methodToPass);
}
public void callMethod(MethodToPass method) {
for (int i = 1; i < 4; i++) {
method.methodToCall(i);
}
}
}
Again, the most common signatures already exist in the JDK - in this case, it's a Consumer<Integer>.
4 Comments
callmethod.
callMethod?