【问题标题】:Passing Function as an Argument to another Function inside another Class [duplicate]将函数作为参数传递给另一个类中的另一个函数[重复]
【发布时间】:2020-11-04 03:58:42
【问题描述】:

我想将一个函数作为参数传递给另一个类中的另一个函数以执行它并返回它的返回值。以下示例代码显示了我想要做的事情。你能帮我实现这个目标吗?

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*/
}

【问题讨论】:

  • 您可以创建一个全局函数,以便您可以从所有类访问它。我认为这会让思考变得更容易

标签: java


【解决方案1】:
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);
    }
}

你的意思是这样吗? 您将始终需要一个接口(与您要传递的方法具有相同的签名)

【讨论】:

  • myClass.myFunction(this::executeFunction);在这里,您还应该为 executeFunction 传递两个参数,它们是 String、Integer
【解决方案2】:

您可以定义自己的功能接口或使用BiFunction&lt;T, U, R&gt;:

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));
    }
}

样本输出:

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

【讨论】:

    最近更新 更多