Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I am looking for a way to pass a method by reference. I understand that Java does not pass methods as parameters, however, I would like to get an alternative.

I've been told 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());

1 Answer

0 votes
by (46k points)

Check out at the command pattern.

// NOTE: code not experimented, but I think 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");

    }

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 17, 2019 in Java by Shubham (3.9k points)

Browse Categories

...