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

前端 未结 22 1537
太阳男子
太阳男子 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:17

    Method references using the :: operator

    You can use method references in method arguments where the method accepts a functional interface. A functional interface is any interface that contains only one abstract method. (A functional interface may contain one or more default methods or static methods.)

    IntBinaryOperator is a functional interface. Its abstract method, applyAsInt, accepts two ints as its parameters and returns an int. Math.max also accepts two ints and returns an int. In this example, A.method(Math::max); makes parameter.applyAsInt send its two input values to Math.max and return the result of that Math.max.

    import java.util.function.IntBinaryOperator;
    
    class A {
        static void method(IntBinaryOperator parameter) {
            int i = parameter.applyAsInt(7315, 89163);
            System.out.println(i);
        }
    }
    
    import java.lang.Math;
    
    class B {
        public static void main(String[] args) {
            A.method(Math::max);
        }
    }
    

    In general, you can use:

    method1(Class1::method2);
    

    instead of:

    method1((arg1, arg2) -> Class1.method2(arg1, arg2));
    

    which is short for:

    method1(new Interface1() {
        int method1(int arg1, int arg2) {
            return Class1.method2(arg1, agr2);
        }
    });
    

    For more information, see :: (double colon) operator in Java 8 and Java Language Specification §15.13.

提交回复
热议问题