Java Lambda 表达式源码分析

本文深入探讨Java Lambda表达式的基本概念,包括Lambda表达式、函数式接口和方法引用。接着,通过字节码分析Lambda的实现原理,指出为什么不使用匿名内部类,并介绍invokedynamic指令的作用。最后,总结Lambda在Java中的应用和实现方式。
摘要由CSDN通过智能技术生成

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<Integer, Integer> function = (n1, n2) -> n1 + n2;
    System.out.println(function.applyAsInt(1, 2));

    ToIntBiFunction<Integer, Integer> function2 = Integer::sum;
    System.out.println(function2.applyAsInt(1, 2));
}

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

函数式接口

首先要从 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 类中的抽象方法,不会增加接口的方法数&

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值