lambda表达式中的“ this ”和“ super ”引用与封闭上下文中的引用相同。由于lambda表达式未定义新的作用域,因此 lambda表达式内的“ this ”关键字表示lambda表达式所在的方法的“ this ”参数。
在下面的示例中,this.toString()只调用LambdaTest对象的toString()方法,而不调用Operate实例的toString()方法。
示例
@FunctionalInterfaceinterface 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 表达式
System.out.println("hashcode: " + this.hashCode());
System.out.println("调用 toString(): "+ this.toString());
return num1 + num2;
};
System.out.println("结果: "+ funcInt.func(10, 7));
} @Override
public String toString() {
System.out.println("Super hashcode: " + super.hashCode());
return Integer.toString(super.hashCode());
}
}输出结果
hashcode: 142257191 Super hashcode: 142257191 调用 toString(): 142257191 结果: 17