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表达式只支持函数式接口。也就是只有一个抽象方法的接口