如何在 Java 中將 this 和 super 關鍵字與 lambda 表示式一起使用?
在 lambda 表示式中,“this”和“super”引用與在封閉環境中的引用相同。由於 lambda 表示式未定義新作用域,因此 lambda 表示式中的“this”關鍵字表示 lambda 表示式所在的 method 的“this”引數。
在以下示例中,this.toString() 會呼叫 LambdaTest 物件的 toString() 方法,而不是呼叫 Operate 例項的 toString() 方法。
示例
@FunctionalInterface interface Operate { int func(int num1, int num2); public String toString(); } public class LambdaTest { public static void main(String[] args) { LambdaTest test = new LambdaTest(); test.getResult(); } public void getResult() { Operate op = (num1, num2) -> { // lambda expression System.out.println("This hashcode: " + this.hashCode()); System.out.println("Calling toString(): "+ this.toString()); return num1 + num2; }; System.out.println("Result is: "+ funcInt.func(10, 7)); } @Override public String toString() { System.out.println("Super hashcode: " + super.hashCode()); return Integer.toString(super.hashCode()); } }
輸出
This hashcode: 142257191 Super hashcode: 142257191 Calling toString(): 142257191 Result is: 17
廣告