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