0

I want to pass a function as an argument to another function inside another class to execute it and return its return value. Following sample code shows what I want to do. Can you please help me how can I achieve this?

MyClass myClass = new MyClass();
myClass.myFunction( executeFunction( "name", 123 ) );

public long executeFunction( String a, Integer b ) {
    //do something
    return 321;
}

/* inside MyClass */
public <RetTyp> myFunction( /*accept any function as a parameter with RetTyp as a return data type*/) {
   /*execute method coming in the argument and return its return value*/
}
2
  • 1
    you can create a global function so you can access it from all classes . I think this will make thinks easier Commented Nov 3, 2020 at 19:22
  • 1
    this can help you Commented Nov 3, 2020 at 19:32

2 Answers 2

0
public static class MyTestClass {
    public void main() {
        MyClass myClass = new MyClass();
        myClass.myFunction(this::executeFunction);
    }

    public long executeFunction(String a, Integer b) {
        //do something
        return 321;
    }
}

public static class MyClass<T> {
    public T myFunction(MyFunctionInterface<T> func) {
        return func.run("", 10);
    }

    public interface MyFunctionInterface<T> {
        T run(String a, Integer b);
    }
}

You mean like this? You will always need an interface for this (With the same signature as your method you want to pass)

Sign up to request clarification or add additional context in comments.

1 Comment

myClass.myFunction(this::executeFunction); here you should also pass two arguments for executeFunction that are String, Integer
0

You may define your own functional interface or use BiFunction<T, U, R>:

import java.util.*;
import java.util.function.*;

public class MyClass {

    @FunctionalInterface
    static interface MyFunction<R, T1, T2> {
        R apply(T1 arg1, T2 arg2);
    }
    // static
    public static <R, T1, T2> R myFunction(MyFunction<R, T1, T2> function, T1 arg1, T2 arg2) {
        return function.apply(arg1, arg2);
    }

    // instance
    public  <T1, T2, R> R myBiFunction(BiFunction<T1, T2, R> function, T1 arg1, T2 arg2) {
        return function.apply(arg1, arg2);
    }
    public static long executeFunction(String a, Integer b) {
        System.out.println(a + ", b=" + b);
        return 123L * a.length() * b;
    }

    public static void main(String args[]) {
        System.out.println(myFunction(MyClass::executeFunction, "guess", 100));
        
        System.out.println(myFunction((List<String> a, String b) -> a.indexOf(b), Arrays.asList("abc", "def", "xyz"), "opq"));
        System.out.println(new MyClass().myBiFunction(MyClass::executeFunction, "bi", 999));
    }
}

Output of sample:

guess, b=100
61500
-1
bi, b=999
245754

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.