【问题标题】:Understanding method references [duplicate]了解方法参考[重复]
【发布时间】:2016-07-01 14:06:17
【问题描述】:

我有以下例子:

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

但是为什么前。 2作品? Car 类中的方法 getColorapply 方法签名不同,我预计此处会出现编译时错误。

【问题讨论】:

  • 您可以将方法getColor 视为具有传递给该方法的隐式this 参数。有些语言明确表示这一点。所以你基本上有一个函数,它接受一个Car 的实例并返回一个String

标签: java-8 method-reference


【解决方案1】:

Car 类中的 getColor 方法与 apply 方法签名不同,我预计会在此处出现编译时错误。

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

【讨论】:

  • 假设我有一个带有两个参数的实例方法。它实际上是否有三个参数,第一个参数是该方法所属的实例?
  • 如果有多个参数,第一个参数总是类实例。
猜你喜欢
  • 2012-11-22
  • 1970-01-01
  • 2022-06-21
  • 2021-03-10
  • 2020-12-18
  • 2021-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多