Java Pass Method as Parameter(Java 传递方法作为参数)
问题描述
我正在寻找一种通过引用传递方法的方法.我知道 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
}
调用如:
setAllComponents(this.getComponents(), changeColor());
setAllComponents(this.getComponents(), changeSize());
推荐答案
编辑:从 Java 8 开始,lambda 表达式 是一个很好的解决方案,就像 otheranswers 已经指出.下面的答案是为 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");
}
}
Pete Kirkham 指出,还有另一种方法可以使用 Visitor.访问者方法涉及更多一些 - 您的节点都需要使用 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 传递方法作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 传递方法作为参数
基础教程推荐
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01