Java Pass Method as Parameter

Edit: as of Java 8, lambda expressions are a nice solution as other answers have pointed out. The answer below was written for Java 7 and earlier…


Take a look at the command pattern.

// 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");
    }
}

Edit: as Pete Kirkham points out, there’s another way of doing this using a Visitor. The visitor approach is a little more involved – your nodes all need to be visitor-aware with an acceptVisitor() method – but if you need to traverse a more complex object graph then it’s worth examining.

Leave a Comment