Java8引入了Lamda表达式。Lamda表达式并不是新功能,只是为了方便代码编写的语法糖。

但,即便是在其他语言已经司空见惯的Lamda表达式,如果在Java中要支持它,还需要考虑各种向下兼容的问题。

简单的说,Java的lamda表达式支持,大约需要考虑2个方面

  1. 需要支持lamda语法,以替代原有的方法匿名类
  2. 需要考虑已有JDK中,如何增加新操作以支持Lamda表达式

对于第一点的回答是FuntionalInterface的Annotation,第二点的回答是default方法。

  • FunctionalInteface

   通过在一个interface上增加@FunctionalInterface, 表示这个接口是特殊interface。其特殊性体现在

  1. 该interface只能有一个抽象方法等待子类实现
  2. 之后,此interface对应的对象,可以是lamda表达式
  3. lamda表达式必须与此interface中唯一的抽象方法签名相一致
 1 @FunctionalInterface
 2 public interface ITest {
 3     void sayHello(String name);  
 4 }
 5 
 6 public class TestLamda {
 7         public static String name = "test";
 8         public static void testRun2(ITest test){
 9             test.sayHello(name);
10         }
11         public static void main(String[] args) {
12             testRun2(test->System.out.println(test));
13         }
14 }
Lamda举例

相关文章:

  • 2022-12-23
  • 2022-02-24
  • 2022-03-02
  • 2021-10-14
  • 2022-12-23
  • 2021-10-26
  • 2021-12-19
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-10
  • 2022-12-23
  • 2021-08-01
  • 2022-02-19
  • 2021-12-13
相关资源
相似解决方案