Java Pass Method as Parameter

后端 未结 16 1336
滥情空心
滥情空心 2020-11-22 02:17

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

16条回答
  •  孤城傲影
    2020-11-22 02:51

    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.

提交回复
热议问题