如何将一个函数作为参数传递给另一个函数 [英] How to pass a function as an parameter to another function
本文介绍了如何将一个函数作为参数传递给另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个函数作为参数传递给另一个函数.例如:
I would like pass a function as an parameter to another function. For example:
void myFunction(boolean coondition, void function())
{
if(condition) {
function();
}
}
在Java 8中有可能吗?
It this possible in Java 8?
推荐答案
不,您不能传递方法.
但是有一个简单的解决方法:传递一个Runnable.
But there is a simple workaround: pass a Runnable.
void myFunction(boolean coondition, Runnable function)
{
if(condition) {
function.run();
}
}
并这样称呼:(使用旧语法)
and call it like this: (using the old syntax)
myFunction(condition, new Runnable() {
@Override
public void run() {
otherFunction();
}
});
或在Java 8中使用新的lambda语法(通常是上述的简写形式):
or using the new lambda syntax in Java 8 (which is mostly shorthand for the above):
myFunction(condition, () -> {otherFunction();}}
这篇关于如何将一个函数作为参数传递给另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文