我正在寻找一种通过引用传递方法的方法.我知道Java不会将方法作为参数传递,但是,我想获得一个替代方案.
我被告知接口是将方法作为参数传递的替代方法,但我不明白接口如何通过引用充当方法.如果我理解正确,接口只是一组未定义的抽象方法.我不希望每次都发送需要定义的接口,因为几种不同的方法可以使用相同的参数调用相同的方法.
我想要完成的是类似的事情:
public void setAllComponents(Component[] myComponentArray, Method myMethod) {
for (Component leaf : myComponentArray) {
if (leaf instanceof Container) { //recursive call if Container
Container node = (Container) leaf;
setAllComponents(node.getComponents(), myMethod);
} //end if node
myMethod(leaf);
} //end looping through components
}
Run Code Online (Sandbox Code Playgroud)
调用如:
setAllComponents(this.getComponents(), changeColor());
setAllComponents(this.getComponents(), changeSize());
Run Code Online (Sandbox Code Playgroud) 请考虑以下Scala代码:
package scala_java
object MyScala {
def setFunc(func: Int => String) {
func(10)
}
}
Run Code Online (Sandbox Code Playgroud)
现在在Java中,我希望MyScala用作:
package scala_java;
public class MyJava {
public static void main(String [] args) {
MyScala.setFunc(myFunc); // This line gives an error
}
public static String myFunc(int someInt) {
return String.valueOf(someInt);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,上述方法不起作用(正如预期的那样,因为Java不允许函数式编程).在Java中传递函数最简单的解决方法是什么?我想要一个通用的解决方案,适用于具有任意数量参数的函数.
编辑:Java 8的语法是否比下面讨论的经典解决方案更好?