Passing function as a parameter in java

后端 未结 6 996
南笙
南笙 2020-11-28 22:13

I\'m getting familiar with Android framework and Java and wanted to create a general \"NetworkHelper\" class which would handle most of the networking code enabling me to ju

6条回答
  •  孤独总比滥情好
    2020-11-28 22:35

    Yes, an interface is the best way IMHO. For example, GWT uses the command pattern with an interface like this:

    public interface Command{
        void execute();
    }
    

    In this way, you can pass function from a method to another

    public void foo(Command cmd){
      ...
      cmd.execute();
    }
    
    public void bar(){
      foo(new Command(){
         void execute(){
            //do something
         }
      });
    }
    

提交回复
热议问题