Java Pass Method as Parameter

700    Asked by PavithraShah in Java , Asked on Mar 24, 2021

I want to know to pass a method by reference. I know that Java does not pass methods as parameters, however, I would like to get an alternative.

Someone told me that 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

}

invoked such as:

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

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

Answered by Ota Azuma

Your Answer

Interviews

Parent Categories