我有以下示例:
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;
}
}
}
例如。自方法 getCarColor
起 1 个有效在CarUtils
类具有与 apply
相同的方法签名和返回类型Function
中的方法界面。
但是为什么前。 2作品?方法getColor
在Car
类与 apply
不同方法签名,我希望在这里得到一个编译时错误。
最佳答案
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,并返回一个字符串。因此这与 Function<Car, String>
中 apply() 的签名匹配.
关于java-8 - 了解方法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38147508/