Java 传递方法作为参数 [英] Java Pass Method as Parameter

查看:43
本文介绍了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 传递方法作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆