What's the nearest substitute for a function pointer in Java?

前端 未结 22 1782
太阳男子
太阳男子 2020-11-22 15:32

I have a method that\'s about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that\'s going to change one li

22条回答
  •  天涯浪人
    2020-11-22 16:19

    The open source safety-mirror project generalizes some of the above mentioned solutions into a library that adds functions, delegates and events to Java.

    See the README, or this stackoverflow answer, for a cheat sheet of features.

    As for functions, the library introduces a Fun interface, and some sub-interfaces that (together with generics) make up a fluent API for using methods as types.

    Fun.With0Params myFunctionField = "   hello world   "::trim;`  
    Fun.With2Params equals = Objects::equals;`  
        
    public void foo(Fun.With1ParamAndVoid printer) throws Exception {
        printer.invoke("hello world);
    }  
    
    public void test(){
        foo(System.out::println);
    }  
    

    Notice:

    1. that you must choose the sub-interface that matches the number of parameters in the signature you are targeting. Fx, if it has one parameter, choose Fun.With1Param.
    2. that Generics are used to define A) the return type and B) the parameters of the signature.

    Also, notice that the signature of the Method Reference passed to the call to the foo() method must match the the Fun defined by method Foo. If it do not, the compiler will emit an error.

提交回复
热议问题