Java Pass方法作为参数 [英] Java Pass Method as Parameter
问题描述
我正在寻找一种通过引用传递方法的方法。我知道Java不会将方法作为参数传递,但是,我想获得一个替代方案。
I am looking for a way to pass a method by reference. I understand that Java does not pass methods as parameters, however, I would like to get an alternative.
我被告知接口是将方法作为参数传递的替代方法,但我不明白接口如何通过引用充当方法。如果我理解正确,接口只是一组未定义的抽象方法。我不想每次都发送需要定义的接口,因为几种不同的方法可以使用相同的参数调用相同的方法。
I've been told interfaces are the alternative to passing methods as parameters but I don't understand how an interface can act as a method by reference. If I understand correctly an interface is simply an abstract set of methods that are not defined. I don't want to send an interface that needs to be defined every time because several different methods could call the same method with the same parameters.
我想要什么完成类似于:
What I would like to accomplish is something similar to this:
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
}
调用如: / p>
invoked such as:
setAllComponents(this.getComponents(), changeColor());
setAllComponents(this.getComponents(), changeSize());
推荐答案
编辑:截至Java 8, lambda表达式是一个不错的解决方案其他 答案指出。下面的答案是为Java 7及更早版本编写的......
Edit: as of Java 8, lambda expressions are a nice solution as other answers have pointed out. The answer below was written for Java 7 and earlier...
看一下命令模式。
// NOTE: code not tested, but I believe this is valid java...
public class CommandExample
{
public interface Command
{
public void execute(Object data);
}
public class PrintCommand implements Command
{
public void execute(Object data)
{
System.out.println(data.toString());
}
}
public static void callCommand(Command command, Object data)
{
command.execute(data);
}
public static void main(String... args)
{
callCommand(new PrintCommand(), "hello world");
}
}
编辑:为< a href =https://stackoverflow.com/questions/2186931/java-pass-method-as-parameter/2186993#2186993> Pete Kirkham指出,还有另一种方法是使用访客。访问者方法更复杂 - 您的节点都需要通过 acceptVisitor()
方法访问者 - 但是如果您需要遍历更复杂的对象图,那么值得研究。
as Pete Kirkham points out, there's another way of doing this using a Visitor. The visitor approach is a little more involved - your nodes all need to be visitor-aware with an acceptVisitor()
method - but if you need to traverse a more complex object graph then it's worth examining.
这篇关于Java Pass方法作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!