Java Pass Method as Parameter

后端 未结 16 1345
滥情空心
滥情空心 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:47

    I didn't find any example explicit enough for me on how to use java.util.function.Function for simple method as parameter function. Here is a simple example:

    import java.util.function.Function;
    
    public class Foo {
    
      private Foo(String parameter) {
        System.out.println("I'm a Foo " + parameter);
      }
    
      public static Foo method(final String parameter) {
        return new Foo(parameter);
      }
    
      private static Function parametrisedMethod(Function function) {
        return function;
      }
    
      public static void main(String[] args) {
        parametrisedMethod(Foo::method).apply("from a method");
      }
    }
    

    Basically you have a Foo object with a default constructor. A method that will be called as a parameter from the parametrisedMethod which is of type Function.

    • Function means that the function takes a String as parameter and return a Foo.
    • The Foo::Method correspond to a lambda like x -> Foo.method(x);
    • parametrisedMethod(Foo::method) could be seen as x -> parametrisedMethod(Foo.method(x))
    • The .apply("from a method") is basically to do parametrisedMethod(Foo.method("from a method"))

    Which will then return in the output:

    >> I'm a Foo from a method
    

    The example should be running as is, you can then try more complicated stuff from the above answers with different classes and interfaces.

提交回复
热议问题