Java Pass Method as Parameter

后端 未结 16 1324
滥情空心
滥情空心 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 03:01

    First define an Interface with the method you want to pass as a parameter

    public interface Callable {
      public void call(int param);
    }
    

    Implement a class with the method

    class Test implements Callable {
      public void call(int param) {
        System.out.println( param );
      }
    }
    

    // Invoke like that

    Callable cmd = new Test();
    

    This allows you to pass cmd as parameter and invoke the method call defined in the interface

    public invoke( Callable callable ) {
      callable.call( 5 );
    }
    

提交回复
热议问题