我在研究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;
}

max是一个方法指针吗?一个正常的静态方法如何转换为IntBinaryOperator?


当前回答

::被称为方法引用。假设我们想调用类Purchase的calculatePrice方法。那么我们可以写成:

Purchase::calculatePrice

它也可以被视为lambda表达式的一种简写形式,因为方法引用被转换为lambda表达式。

其他回答

是的,那是真的。操作符用于方法引用。因此,可以使用它从类中提取静态方法,也可以从对象中提取方法。相同的操作符甚至可以用于构造函数。下面的代码示例演示了这里提到的所有情况。

Oracle的官方文档可以在这里找到。

在本文中,您可以更好地概述JDK 8的更改。在方法/构造函数引用部分还提供了一个代码示例:

interface ConstructorReference {
    T constructor();
}

interface  MethodReference {
   void anotherMethod(String input);
}

public class ConstructorClass {
    String value;

   public ConstructorClass() {
       value = "default";
   }

   public static void method(String input) {
      System.out.println(input);
   }

   public void nextMethod(String input) {
       // operations
   }

   public static void main(String... args) {
       // constructor reference
       ConstructorReference reference = ConstructorClass::new;
       ConstructorClass cc = reference.constructor();

       // static method reference
       MethodReference mr = cc::method;

       // object method reference
       MethodReference mr2 = cc::nextMethod;

       System.out.println(cc.value);
   }
}

这是Java 8中的一个方法引用。Oracle文档在这里。

如文件所述……

方法引用Person::compareByAge是对静态对象的引用 方法。 类的实例方法的引用示例 特定对象:

class ComparisonProvider {
    public int compareByName(Person a, Person b) {
        return a.getName().compareTo(b.getName());
    }

    public int compareByAge(Person a, Person b) {
        return a.getBirthday().compareTo(b.getBirthday());
    }
}

ComparisonProvider myComparisonProvider = new ComparisonProvider();
Arrays.sort(rosterAsArray, myComparisonProvider::compareByName); 

方法引用myComparisonProvider::compareByName调用方法compareByName 它是对象myComparisonProvider的一部分。JRE会推断 方法类型参数,在本例中为(Person, Person)。

返回减少(数学:max);不等于返回reduce(max());。

但它的意思是这样的:

IntBinaryOperator myLambda = (a, b)->{(a >= b) ? a : b};//56 keystrokes I had to type -_-
return reduce(myLambda);

如果你这样写,你可以节省47个按键:

return reduce(Math::max); // Only 9 keystrokes ^_^

通常,我们会使用Math调用reduce方法。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编译器“检测”到你想要实现一个接受两个int型并返回一个int型的方法。这等价于接口IntBinaryOperator的唯一方法的形式参数(要调用的方法reduce的参数)。所以编译器会帮你完成剩下的工作——它只是假设你想要实现IntBinaryOperator。

但作为数学。max(int, int)本身满足IntBinaryOperator的形式要求,它可以直接使用。因为Java 7没有任何允许方法本身作为参数传递的语法(你只能传递方法结果,但不能传递方法引用),所以Java 8引入了::语法来引用方法:

reduce(Math::max);

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

(参见Lambda表达式的翻译)

在旧的Java版本中,你可以使用:而不是"::"或lambd:

public interface Action {
    void execute();
}

public class ActionImpl implements Action {

    @Override
    public void execute() {
        System.out.println("execute with ActionImpl");
    }

}

public static void main(String[] args) {
    Action action = new Action() {
        @Override
        public void execute() {
            System.out.println("execute with anonymous class");
        }
    };
    action.execute();

    //or

    Action actionImpl = new ActionImpl();
    actionImpl.execute();
}

或者传递给方法:

public static void doSomething(Action action) {
    action.execute();
}