Java 8中的方法参考 [英] Method reference in Java 8
问题描述
public class Car {
private int maxSpeed;
public Car(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
public int getMaxSpeed() {
return maxSpeed;
}
}
我们可以对汽车列表进行排序
We can sort a list of cars by,
Car carX = new Car(155);
Car carY = new Car(140);
List<Car> cars = new ArrayList<>();
cars.add(carX);
cars.add(carY);
cars.sort(Comparator.comparing(Car::getMaxSpeed));
如果看到方法Comparator.comparing
的签名,则输入参数类型为Function<? super T, ? extends U>
If we see the signature of the method Comparator.comparing
, the input parameter type is Function<? super T, ? extends U>
在上面的示例中,如何将Car::getMaxSpeed
强制转换为Function<? super T, ? extends U>
,而以下内容无法编译?
In the above example, how is Car::getMaxSpeed
being cast to Function<? super T, ? extends U>
while the following does not compile?
Function<Void, Integer> function = Car::getMaxSpeed;
推荐答案
这是因为getMaxSpeed
方法是Function<Car, Integer>
.
即:
<Car, Integer> Comparator<Car> java.util.Comparator.comparing(
Function<? super Car, ? extends Integer> keyExtractor
)
注意
为了从具有::
习惯用法的Car
实例引用getMaxSpeed
,您必须声明一个具有签名:getMaxSpeed(Car car)
的Car
方法.
In order to reference getMaxSpeed
from an instance of Car
with the ::
idiom, you would have to declare a Car
method with signature: getMaxSpeed(Car car)
.
这篇关于Java 8中的方法参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!