Java 8 理解方法引用

Java 8 理解方法引用,java-8,method-reference,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(Ca

我举了以下例子:

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;
        }
    }
}
公共类应用程序{
公共静态void main(字符串[]args){
列表=数组。asList(新车(“绿色”)、新车(“蓝色”)、新车(“白色”);
//例1
List carColors1=List.stream().map(CarUtils::getCarColor).collect(Collectors.toList());
//例2
List carColors2=List.stream().map(Car::getColor).collect(Collectors.toList());
}
静态类CarUtils{
静态字符串getCarColor(汽车){
return car.getColor();
}
}
静态级轿车{
私有字符串颜色;
公共汽车(字符串颜色){
这个颜色=颜色;
}
公共字符串getColor(){
返回颜色;
}
}
}
例1在
CarUtils
类中的方法
getCarColor
Function
接口中的
apply
方法具有相同的方法签名和返回类型时起作用

但是为什么Ex.2有效呢?
Car
类中的方法
getColor
具有不同于
apply
的方法签名,我希望在这里得到编译时错误

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


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

您可以将方法
getColor
视为具有传递到方法中的隐式
参数。一些语言明确了这一点。基本上你有一个函数,它接受一个
Car
的实例,并返回一个
字符串。它实际上是否有三个参数,第一个参数将是该方法所属的实例?如果有多个参数,第一个参数将始终是类实例。