理解方法参考

时间:2016-07-01 14:06:17

标签: java-8 method-reference

我有以下示例:

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工作,因为getCarColor类中的方法CarUtils具有与apply接口中的Function方法相同的方法签名和返回类型。

但为什么Ex。 2作品? getColor类中的方法Carapply方法签名不同,我希望在此处收到编译时错误。

1 个答案:

答案 0 :(得分:2)

  

Car类中的方法getColor与apply方法签名不同,我希望在这里得到编译时错误。

不是真的。 Car.getColor()是一种实例方法。您可以将其视为一个函数,它接受一个参数:this,类型为Car,并返回一个String。因此,它与Function<Car, String>中的apply()的签名匹配。

相关问题