java - 有没有办法在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()) {
}
}
是否有可能做到这一点??如果是,我将如何实现这一目标
解决方案
你不能那样做。将现有方法作为参数传递的一种方法是使目标方法本身采用函数式接口类型,然后您可以为要作为参数传递的方法使用方法引用:
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
}
推荐阅读
- visual-studio-code - 我正在弹出这个 VSCode “Arduino Core for SAMD21 and SAMD51 CPU”
- debugging - pycharm 2020.3 中的断点
- swift - WKWebView macOS 问题
- python - 如何获取列表中匹配元素的壁橱索引
- reactjs - 如何使用 Tailwind 和 React 为渐变添加自定义颜色?
- android - Android Place SDK 受限 API 密钥不起作用
- haskell - 为什么我不能在任何地方都使用 undefined ?
- javascript - 为什么这个 Django 模板没有接收到上下文?
- python - 如何正确使用来自 opencv 的针图像?
- twilio - 在连接到代理小部件 - 我正在添加一个电话号码,但它没有达到那个号码。日志显示超时:可选 [30]