Method reference in Java 8

前端 未结 5 1011
梦如初夏
梦如初夏 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:36

    If you want to create a method reference for a method that takes no parameters, such as a method already bound to an instance, you should use a Supplier, not a Function:

    Function f1 = Car::getMaxSpeed;
    
    Car carx = new Car(42);
    Supplier f2 = carx::getMaxSpeed; 
    

    In the method reference carX::getMaxSpeed, the "implicit" this-parameter of the function is already bound to carx, so you are left with a no-parameter-function (which, by the way, can not be used in a Comparator), and in Java 8, a no-parameter-function is just a Supplier.

    Similarly, if you have a method that returns void, you end up with a Comsumer:

    Consumer f3 = carx::setMaxSpeed;
    

提交回复
热议问题