小编典典

Java 8中的::(双冒号)运算符

java

我正在探索Java 8源代码,发现代码的这一特殊部分非常令人惊讶:

//defined in IntPipeline.java
@Override
public final OptionalInt reduce(IntBinaryOperator op) {
    return evaluate(ReduceOps.makeInt(op));
}

@Override
public final OptionalInt max() {
    return reduce(Math::max); //this is the gotcha line
}

//defined in Math.java
public static int max(int a, int b) {
    return (a >= b) ? a : b;
}

Math::max类似方法指针的东西吗?普通static方法如何转换为IntBinaryOperator


阅读 875

收藏
2020-02-26

共1个答案

小编典典

通常,可以reduce使用Math.max(int, int)以下方法调用该方法:

reduce(new IntBinaryOperator() {
    int applyAsInt(int left, int right) {
        return Math.max(left, right);
    }
});

仅调用就需要很多语法Math.max。那就是lambda表达式起作用的地方。从Java 8开始,它允许以更短的方式执行相同的操作:

reduce((int left, int right) -> Math.max(left, right));

这是如何运作的?Java编译器“检测”你要实现一个接受两个ints并返回一个的方法int。这等效于接口的唯一方法IntBinaryOperator(reduce你要调用的方法的参数)的形式参数。因此,编译器会为你完成其余工作-只是假设你要实现IntBinaryOperator

但是,由于Math.max(int, int)其本身满足的形式要求IntBinaryOperator,因此可以直接使用。由于Java 7没有允许将方法本身作为参数传递的语法(你只能传递方法结果,而不能传递方法引用),因此::Java 8中引入了语法来引用方法:

reduce(Math::max);

注意,这将由编译器解释,而不是在运行时由JVM解释!尽管它为所有三个代码段生成了不同的字节码,但它们在语义上是相等的,因此,后两个可以视为上述实现的简短版本(可能效率更高)IntBinaryOperator

2020-02-26