Java 8:将匿名类转换为Lambda表达式
生活随笔
收集整理的這篇文章主要介紹了
Java 8:将匿名类转换为Lambda表达式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
將匿名類(實現一種方法)重構為lambda表達式,可使您的代碼更簡潔明了。 例如,這是Runnable及其lambda等效項的匿名類:
// using an anonymous class Runnable r = new Runnable() {@Overridepublic void run() {System.out.println("Hello");} };// using a lambda expression Runnable r2 = () -> System.out.println("Hello");但是,它并不總是那么簡單!
這里有一些陷阱:
1.不同的作用域規則
匿名類和lambda表達式之間有不同的作用域規則。 例如,在lambda表達式中, this和super在詞法上是作用域的,這意味著它們是相對于封閉類的,而在匿名類中,它們是相對于匿名類本身的。 同樣,在lambda表達式中聲明的局部變量將與在封閉類中聲明的變量發生沖突,但是在匿名類中,允許它們在封閉類中對變量進行屏蔽 。 這是一個例子:
int foo = 1; Runnable r = new Runnable() {@Overridepublic void run() {// this is ok!int foo = 2;} };Runnable r2 = () -> {// compile error: Lambda expression's local variable foo cannot// redeclare another local variable defined in an enclosing scope.int foo = 2; };2.重載方法
如果您有重載的方法,則使用lambda表達式可能會導致方法調用不明確,并且需要顯式轉換。 這是一個例子:
// Functional interface interface Task {public void execute(); }// Overloaded methods public static void go(final Runnable r) {r.run(); } public static void go(final Task t) {t.execute(); }// Calling the overloaded method:// When using an anonymous class, there is no ambiguity because // the type of the class is explicit at instantiation go(new Task() {@Overridepublic void execute() {System.out.println("Hello");} });// When using a lambda expression, there is a compile error! // The method go(Runnable) is ambiguous go(() -> {System.out.println("Hello"); });// This ambiguity can be solved with an explicit cast go((Task)() -> {System.out.println("Hello"); });翻譯自: https://www.javacodegeeks.com/2016/06/java-8-converting-anonymous-classes-lambda-expressions.html
總結
以上是生活随笔為你收集整理的Java 8:将匿名类转换为Lambda表达式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 360民间电脑专家加入(360电脑专家咨
- 下一篇: 我们处理了10亿个Java记录的错误-这