理解Java的lamda表达式实现

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举例

 

  • Default方法

default方法只能在interface中声明。default方法使得interface也可以定义已经实现的方法。那么问题来了。interface为什么一定需要这个特性?java的interface不就是应该都只有抽象方法吗?

考虑一下这个例子

1             List<Integer> alist = new ArrayList<Integer>();
2             alist.add(1);
3             alist.add(2);
4             alist.add(3);
5             alist.add(4);
6             alist.forEach((s)->System.out.println(s));    
List的例子

  List是JDK java.util的一个接口。此接口由来已久。如果要在其中引入forEach方法,而且支持使用lamda表达式,必须对List进行一些改变。但是,JDK要向下兼容,一旦对已知的List增加接口,势必无法保证兼容性。所以,出于这个原因,想办法增加了default方法。这使得一个接口可以定义默认方法,以保全JDK原有的接口可以继续向下兼容。

 

posted on 2017-06-22 09:48  daition  阅读(688)  评论(0编辑  收藏  举报

导航