首页 > 解决方案 > 有没有办法在java中将对象的方法作为参数传递?

问题描述

我有 1 类如下所述:

public class mathAdd {

public int add(int val1,int val2) {
    int res = 0;
    res = val1+val2;
    return res;

}

}

我想将方法​​“add”作为参数传递,类似于下面代码中显示的方式?

public class test4 {

    public static void main(String[] args) {
        test4 t4 = new test4();
        mathAdd m1 = new mathAdd();
        t4.testMeth(m1.add);
    }
    public void testMeth(Object obj.meth()) {

    }

}

是否有可能做到这一点??如果是,我将如何实现这一目标

标签: java

解决方案


你不能那样做。将现有方法作为参数传递的一种方法是使目标方法本身采用函数式接口类型,然后您可以为要作为参数传递的方法使用方法引用:

public void testMeth(IntBinaryOperator method) {
    //IntBinaryOperator defines a method that takes 2 ints and returns an int
    //And that's the signature matching mathAdd#add

    //you can call the method using something like
    int result = method.applyAsInt(int1, int2);
}

然后在main

public static void main(String[] args) {
    test4 t4 = new test4();
    mathAdd m1 = new mathAdd();

    t4.testMeth(m1::add); //pass the 'add' method
}

推荐阅读