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