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