This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Problem: Java passes methods as arguments

I’m looking for ways to pass methods by reference. I know Java can’t pass methods as arguments, but I’d like an alternative.

I understand that interfaces are an alternative way to pass parameters to methods, but I don’t understand how interfaces can be made to behave like methods by reference. If I understand it correctly, an interface is just a simple, undefined set of abstract methods. I don’t want to pass in an interface that needs to be defined each time because several different methods might call the same method with the same parameters.

What I want to accomplish is something like this:

public void setAllComponents(Component[] myComponentArray, Method myMethod) {
    for (Component leaf : myComponentArray) {
        if (leaf instanceofContainer) { Container node = (Container) leaf; setAllComponents(node.getComponents(), myMethod); } myMethod(leaf); }}Copy the code

Call it like this:

setAllComponents(this.getComponents(), changeColor());
setAllComponents(this.getComponents(), changeSize());
Copy the code

answer

Edit: As other answers point out, lambda expressions are a good solution in Java 8. The answers below were written for Java 7 and previous versions

Take a look at the Command pattern.

// Note: the code is not tested because I think it is legitimate Java code
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"); }}Copy the code

Edit: As Pete Kirkham points out, another way is to use the Visitor. The Visitor method is a bit complicated because all of your nodes need to use the acceptVisitor() method to implement visitor-aware. But if you need to walk through a more complex object graph, it’s worth a try.

The article translated from Stack Overflow:stackoverflow.com/questions/2…