我的问题是Lambda表达式和方法引用都与函数接口有关,它们只是提供了其实现。现在当我编写以下代码时:
我的getter方法为什么不需要任何参数就能正常工作呢?这是因为它符合函数式接口的规范。
class Apple{
private int weight;
private String color;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}}
如果我写:
Function<Apple, Integer> getWeight = Apple::getWeight;
或者
appleList.stream().map(Apple::getColor).collect(toList());
我的getter方法为什么不需要任何参数就能正常工作呢?这是因为它符合函数式接口的规范。
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);}
它需要一个参数并返回一些内容,当getter像这样时,它应该实际工作:
public int getWeight(Apple a) {
return a.weight;
}
我有点困惑,提前感谢。