Java Lambda 表达式源码分析 您所在的位置:网站首页 欧美人穿西装丑 Java Lambda 表达式源码分析

Java Lambda 表达式源码分析

2023-04-07 12:19| 来源: 网络整理| 查看: 265

Lambda 表达式是什么?JVM 内部究竟是如何实现 Lambda 表达式的?为什么要这样实现?

基本概念 Lambda 表达式

下面的例子中, () -> System.out.println("1") 就是一个Lambda 表达式。Java 8 中每一个Lambda 表达式必须有一个函数式接口与之对应。Lambda表达式就是函数式接口的一个实现。

@Test public void test0() { Runnable runnable = () -> System.out.println("1"); runnable.run(); ToIntBiFunction function = (n1, n2) -> n1 + n2; System.out.println(function.applyAsInt(1, 2)); ToIntBiFunction function2 = Integer::sum; System.out.println(function2.applyAsInt(1, 2)); }

大致形式就是 (param1, param2, param3, param4…) -> { doing…… };

函数式接口

首先要从 FunctionalInterface 注解讲起,详情见 Annotation Type FunctionalInterface 。

An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Conceptually, a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.

简单总结一下函数式接口的特征:

FunctionalInterface 注解标注一个函数式接口,不能标注类,方法,枚举,属性这些。 如果接口被标注了 @FunctionalInterface,这个类就必须符合函数式接口的规范。 即使一个接口没有标注 @FunctionalInterface,如果这个接口满足函数式接口规则,依旧可以被当作函数式接口。 注意:interface 中重写 Object 类中的抽象方法,不会增加接口的方法数,因为接口的实现类都是 Object 的子类。

我们可以看到 Runnable 接口,里面只有一个抽象方法 run() ,则这个接口就是一个函数式接口。

@FunctionalInterface public interface Runnable { public abstract void run(); } 方法引用

所谓方法引用,是指如果某个方法签名和接口恰好一致,就可以直接传入方法引用。文章开头的示例中,下面这块代码就是方法引用。

ToIntBiFunction function2 = Integer::sum;

java.lang.Integer#sum 的实现如下:

public static int sum(int a, int b) { return a + b; }

比如我们计算一个 Stream 的和,可以直接传入 Integer::sum 这个方法引用。

@Test public void test1() { Integer sum = IntStream.range(0, 10).boxed().reduce(Integer::sum).get(); System.out.println(sum); }

上面的代码中,为什么可以直接在 reduce 方法中传入 Integer::sum 这个方法引用呢?这是因为 reduce 方法的入参就是 BinaryOperator 的函数式接口。

Optional reduce(BinaryOperator accumulator);

BinaryOperator 是继承自 BiFunction ,定义如下:

@FunctionalInterface public interface BiFunction { R apply(T t, U u); default BiFunction andThen(Function


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有