如何使用 Java 中的 lambda 從封閉類訪問變數?
由 lambda 表示式的封閉作用域定義的變數可以在 lambda 表示式中訪問。lambda 表示式可以訪問封閉類定義的例項、靜態變數和方法。它還可以訪問 "this" 變數(隱式和顯式),該變數可能是封閉類的例項。lambda 表示式還可以設定靜態或例項變數的值。
示例
interface SimpleInterface {
int func();
}
public class SimpleLambdaTest {
static int x = 50;
public static void main(String[] args) {
SimpleInterface test = () -> x; // Accessing of static variable using lambda
System.out.println("Accessing static variable 'x': " + test.func());
test = () -> { // Setting the value to variable using lambda
return x = 80;
};
System.out.println("Setting value for 'x': " + test.func());
}
}輸出
Accessing static variable 'x': 50 Setting value for 'x': 80
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP