我正在寻找通过引用传递方法的方法.我知道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
}

例如:

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

推荐答案

Edit:正如otheranswers所指出的,在Java8中,lambda expressions是一个很好的解决方案.下面的答案是为Java 7和更早版本编写的...


看看这command pattern个.

// 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");
    }
}

Edit:等于Pete Kirkham points out,还有另一种使用Visitor的方法.访问者方法稍微复杂一些-使用acceptVisitor()方法,您的 node 都需要是访问者感知的-但是如果您需要遍历更复杂的对象图,那么它是值得研究的.

Java相关问答推荐

Java Swing绘制gif作为多个JSYS和JLabels的背景

无法运行Java(已解决)

为什么我的画布没有显示在PFA应用程序中?

如何审查Java dtos中的自定义注释字段?

Java中后期绑定的替代概念

如果一个子类没有构造函数,超类也没有构造函数,那么为什么我可以构造子类的实例呢?

Junit with Mockito for java

我无法将附件发送到NetBeans之外

Kubernetes的Java客户端检索状态.处于终止状态的Pod的阶段';正在运行';

滚动视图&不能在alert 对话框中工作(&Q;&Q;)

R.id.main给我一个红色错误,无法解析MainActivity.java中的符号main

为什么JAVA&S清洁器使用链表而不是并发HashSet?

暂停计时器

试着做一个2x2的魔方求解算法,我如何找到解路径(DFS)?

如何解释Java中for-each循环中对Iterable的强制转换方法引用?

如何从日期中截取时间并将其传递给组件?

如何仅使用键/ID的一部分(组合)高效地返回映射值?

将stringBuilder + forloop转换为stream + map

通过Java列表中的某些字段搜索值

插入中的JOOQ序列,设置为VS值