Java 传递方法作为参数

新手上路,请多包涵

我正在寻找一种通过引用传递方法的方法。我知道 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());

原文由 Mac 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 384
2 个回答

_编辑_:从 Java 8 开始, lambda 表达式 是一个很好的解决方案,正如 其他 答案 所指出的那样。下面的答案是为 Java 7 及更早版本编写的…


看看 命令模式

 // 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() 方法来感知访问者——但如果你需要遍历更复杂的对象图,那么它值得研究。

原文由 Dan Vinton 发布,翻译遵循 CC BY-SA 3.0 许可协议

在 Java 8 中,您现在可以使用 Lambda 表达式 和方法引用更轻松地传递方法。首先,一些背景知识:功能接口是一个只有一个抽象方法的接口,尽管它可以包含任意数量的 默认方法(Java 8 中的新方法)和静态方法。如果不使用 lambda 表达式,lambda 表达式可以快速实现抽象方法,而无需所有不必要的语法。

没有 lambda 表达式:

 obj.aMethod(new AFunctionalInterface() {
    @Override
    public boolean anotherMethod(int i)
    {
        return i == 982
    }
});

使用 lambda 表达式:

 obj.aMethod(i -> i == 982);


以下是 有关 Lambda 表达式的 Java 教程 的摘录:

Lambda 表达式的语法

一个 lambda 表达式包含以下内容:

  • 括在括号中的形式参数的逗号分隔列表。 CheckPerson.test 方法包含一个参数 p,它表示 Person 类的一个实例。

注意:您可以省略 lambda 表达式中参数的数据类型。此外,如果只有一个参数,则可以省略括号。例如,以下 lambda 表达式也是有效的:

>    p -> p.getGender() == Person.Sex.MALE
>       && p.getAge() >= 18
>       && p.getAge() <= 25
>
>   ```
>
> - 箭头令牌, `->`
>
> - 主体,由单个表达式或语句块组成。此示例使用以下表达式:
>
>
>   ```
>    p.getGender() == Person.Sex.MALE
>       && p.getAge() >= 18
>       && p.getAge() <= 25
>
>   ```
>
>
>   如果您指定单个表达式,则 Java 运行时会计算该表达式,然后返回它的值。或者,您可以使用 return 语句:
>
>
>   ```
>    p -> {
>       return p.getGender() == Person.Sex.MALE
>           && p.getAge() >= 18
>           && p.getAge() <= 25;
>   }
>
>   ```
>
>
>    return 语句不是表达式;在 lambda 表达式中,您必须将语句括在大括号 ({}) 中。但是,您不必将 void 方法调用括在大括号中。例如,以下是一个有效的 lambda 表达式:
>
>
>   ```
>    email -> System.out.println(email)
>
>   ```
>
>
> 请注意,lambda 表达式看起来很像方法声明;您可以将 lambda 表达式视为匿名方法——没有名称的方法。

* * *

以下是如何使用 lambda 表达式“传递方法”:

interface I { public void myMethod(Component component); }

class A { public void changeColor(Component component) { // code here }

public void changeSize(Component component) {
    // code here
}

}


class B { public void setAllComponents(Component[] myComponentArray, I myMethodsInterface) { for(Component leaf : myComponentArray) { if(leaf instanceof Container) { // recursive call if Container Container node = (Container)leaf; setAllComponents(node.getComponents(), myMethodInterface); } // end if node myMethodsInterface.myMethod(leaf); } // end looping through components } }


class C { A a = new A(); B b = new B();

public C() {
    b.setAllComponents(this.getComponents(), component -> a.changeColor(component));
    b.setAllComponents(this.getComponents(), component -> a.changeSize(component));
}

}


类 `C` 可以通过使用如下方法引用进一步缩短:

class C { A a = new A(); B b = new B();

public C() {
    b.setAllComponents(this.getComponents(), a::changeColor);
    b.setAllComponents(this.getComponents(), a::changeSize);
}

}

”`

原文由 The Guy with The Hat 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题