java-8 - 了解方法引用

标签 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(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作品?方法getColorCar类与 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/

相关文章:

java8 流和状态

java - 为什么在 Java 8 中对方法参数进行未经检查的转换时,返回类型的泛型会被删除?

java - 流已被操作或关闭 - Java 8

java - 从 LambdaMetafactory 创建 BiConsumer

reflection - kotlin - 将方法引用传递给函数

java-8 - Java8 - 将整数数组转换为单个元素的多个列表

java - 确定 lambda 表达式在 Java 中是无状态的还是有状态的

java - IntFunction<String> 和 Function<Integer, String>

Java - 在没有 lambda 表达式的情况下使用谓词

java - 指定 before/after::operator 的通用方法引用类型