java1.8学习-什么样的匿名内部类能被lambda语法代替?

java1.8好多新的特性真的很有意思,特别是Lambda。在学习的时候发现并不是所有的匿名内部类都可以用Lambda代替。

lambda表达式用得最多的场合就是替代匿名内部类,而实现Runnable接口是匿名内部类的经典例子。lambda表达式的功能相当强大,用()->就可以代替整个匿名内部类。

请看代码:

@Test
public void oldRunable() {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("The old runable now is using!");
}
}).start();
}

而如果使用lambda表达式:

@Test
public void runable() {
new Thread(() -> System.out.println("It's a lambda function!")).start();
}

但问题来了,这个替代匿名内部类的方式并不是所有情况都适合。

翻阅官方文档发现有关Funtional interfaces的说法:

Functional interfaces. The Runnable interface—like the Callable interface, the Comparator interface, and a whole host of other interfaces already defined within Java—is what Java 8 calls a functional interface: it is an interface that requires exactly one method to be implemented in order to satisfy the requirements of the interface. This is how the syntax achieves its brevity, because there is no ambiguity around which method of the interface the lambda is trying to define.

即:Lambda表达式只支持函数式接口。也就是只有一个抽象方法的接口

最新文章

  1. iOS开发,用了ARC,引入非ARC的第三方,报错
  2. video标签的属性和方法总结
  3. 一道原生js题目引发的思考(鼠标停留区块计时)
  4. fir.im Weekly - Swift 3.0 的迁移适配指南
  5. Group的操作
  6. C 实现一个简易的Http服务器
  7. 百度云盘demo
  8. OpenJudge/Poj 1083 Moving Tables
  9. SQL Server 2008 常见异常收集(持续更新)
  10. 常用命令常用sql:SHOWVARIABLESLIKE'character%'
  11. Asp .Net Core 读取appsettings.json配置文件
  12. vue day7 table checkbox 全选
  13. 當 Alexa 遇上 ESP8266 (一)
  14. c# js 删除table原行数据
  15. GraphicsMagick命令
  16. 一. Redis 常用命令
  17. Redis支持的数据类型及相应操作命令:String(字符串),Hash(哈希),List(列表),Set(集合)及zset(sorted set:有序集合)
  18. [Android]通过alias映射所有Busybox命令
  19. MySQL库和表的管理
  20. 『PyTorch』第十六弹_hook技术

热门文章

  1. Jquery选择器大全、属性操作、css操作、文档、事件等
  2. centos 6.2 pptp 客户端 安装(转载)
  3. bzoj 3528 [Zjoi2014]星系调查【树链剖分+数学】
  4. 【UVA - 101】The Blocks Problem(vector+模拟)
  5. ibatais.net 连接 mysql 最全配置写法
  6. BFS(最短路) HDOJ 4308 Saving Princess claire_
  7. AC自动机 HDOJ 2222 Keywords Search
  8. magento controller直接渲染Block 以及传参
  9. *关于TCP长连接,NAT超时,心跳包
  10. 转: ORA-06508 could not find program unit being called: "DBSNMP.BSLN_INTERNAL