Method reference in Java 8

前端 未结 5 1007
梦如初夏
梦如初夏 2021-02-13 15:31
public class Car {

    private int maxSpeed;

    public Car(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public int getMaxSpeed() {
        return maxS         


        
5条回答
  •  走了就别回头了
    2021-02-13 16:33

    The assignment:

    Function function = carX::getMaxSpeed;
    

    does not compile because it's a Supplier, not a Function.

    So then, why does this compile?:

    Comparator.comparing(Car::getMaxSpeed)
    

    Java 8 allows an instance method reference that is a Supplier to be provided where a Function is expected, and the compiler effectively converts the getter method into a function.

    To find out why this is possible, let's look at how we invoke a getter method using reflection:

    System.out.println(Car.class.getMethod("getMaxSpeed").invoke(carX)); // "155"
    

    When calling invoke() on an instance method, we pass the instance to the invoke() method of the getter's Method - there's an implied parameter of the instance type. When looked at it this way, we see that under the hood a getter is really implemented as a Function via the invoke() method.

提交回复
热议问题