测试匿名内部类和lambda表达式的this“指针”
/** * 测试匿名内部类和lambda表达式的this“指针” * 结论: * lambda表达式虽然也会构建一个类,但是内部却没有自己的this指针, * 当在内部使用this指针时,代指的是表达式外部对应的对象 */ public class Test { public static void main(String[] args) { new Test().test1(); } void test1(){ System.out.println("Test对象hashCode=" + this.hashCode()); System.out.println("------------------------------"); f(()->{ System.out.println("lambda内的this:" + this.hashCode()); }); System.out.println("--------------"); f(new Inter1() { @Override public void func() { System.out.println("内部类内的this:" + this.hashCode()); } }); } private static void f(Inter1 i) { i.func(); System.out.println("i.hashCode=" + i.hashCode()); System.out.println("i所属class=" + i.getClass()); } } interface Inter1{ void func(); }
补充:
在Java官方文档里有这样一句话:
Lambda expressions are lexically scoped. This means that they do not inherit any names from a supertype or introduce a new level of scoping. Declarations in a lambda expression are interpreted just as they are in the enclosing environment.
就是说lambda表达式为词法作用域,即它不会从父类继承任何名字,也不会引入新的作用域。
浙公网安备 33010602011771号