Java里面传递方法作为参数| Java Debug 笔记

294 阅读2分钟

本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看 活动链接

问题:Java里面传递方法作为参数

我正在寻找通过引用去传递方法的方式。我知道Java不能把方法作为参数传递,但是,我希望得到一种替代方案。

我知道了接口是一种替代方式,去作为参数传递给方法的,但是我不明白接口是怎么样通过引用,使得可以像方法那样运行的。如果我理解正确的话,接口只是一组简单的、没有定义的抽象方法。我不想传递一个接口,它每次都需要进行定义,因为几个不同的方法可能会调用具有相同参数的相同方法。

我想要完成的是类似这样的事情:

public void setAllComponents(Component[] myComponentArray, Method myMethod) {
    for (Component leaf : myComponentArray) {
        if (leaf instanceof Container) { 
            Container node = (Container) leaf;
            setAllComponents(node.getComponents(), myMethod);
        } 
        myMethod(leaf);
    } 
}

像这样调用:

setAllComponents(this.getComponents(), changeColor());
setAllComponents(this.getComponents(), changeSize());

回答

编辑:正如其他答案所指出的,在Java 8中,lambda表达式是一个很好的解决方案。下面的答案是为了Java 7和之前的版本编写的

看一下 command pattern.

// 注意:代码没有测试过,因为我认为这是合法的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的。Visitor方法有点复杂,因为你的所有节点都需要使用acceptVisitor()方法来实现visitor-aware。但是如果您需要遍历更复杂的对象图,那么它就值得一试。

文章翻译自Stack Overflow:stackoverflow.com/questions/2…