了解方法参考

Understanding method references

我有以下例子:

public class App {
    public static void main( String[] args ) {
        List<Car> list = Arrays.asList(new Car("green"), new Car("blue"), new Car("white"));
        //Ex. 1
        List<String> carColors1 = list.stream().map(CarUtils::getCarColor).collect(Collectors.toList());
        //Ex. 2
        List<String> carColors2 = list.stream().map(Car::getColor).collect(Collectors.toList());
    }

    static class CarUtils {
        static String getCarColor(Car car) {
            return car.getColor();
        }
    }

    static class Car {
        private String color;

        public Car(String color) {
            this.color = color;
        }

        public String getColor() {
            return color;
        }
    }
}

例如。 1 有效,因为 CarUtils class 中的方法 getCarColorFunction 接口中的 apply 方法具有相同的方法签名和 return 类型。

但为什么前。 2作品? Car class 中的方法 getColorapply 方法签名不同,我预计这里会出现编译时错误。

Method getColor in Car class has a different from apply method signature and I expect to get a compile time error here.

不是真的。 Car.getColor() 是一个实例方法。您可以将其视为一个接受一个参数的函数:this,类型为 Car,returns 是一个字符串。所以这与 Function<Car, String>.

中 apply() 的签名匹配