privatevoiddoProcess(int i, Consumer<Integer> consumer) { consumer.accept(i); } publicstaticvoidmain(String[] args) { ThisReferenceExamplethisRefEx=newThisReferenceExample(); thisRefEx.doProcess(10, i -> { System.out.println("Value of i is: " + i); // System.out.println(this); this will not work System.out.println("Can not print this in a static method"); });
thisRefEx.execute(); } // lambda 表达式在静态方法中,无法获取 this 引用 输出: Value of i is: 10 Can not print this in a static method
使用匿名内部类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicstaticvoidmain(String[] args) { ThisReferenceExamplethisRefEx=newThisReferenceExample(); thisRefEx.doProcess(10, newConsumer<Integer>() { @Override publicStringtoString() { return"this is point to a anonymous inner class"; } @Override publicvoidaccept(Integer i) { System.out.println("Value of i is: " + i); System.out.println(this); } }); } // lambda 表达式在匿名内部类中, this 指向当前内部类 输出: Value of i is: 10 this is point to a anonymous inner class
使用成员方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicstaticvoidmain(String[] args) { ThisReferenceExamplethisRefEx=newThisReferenceExample(); thisRefEx.execute(); } privatevoidexecute() { this.doProcess(10, i -> { System.out.println("Value of i is: " + i); System.out.println(this); }); } // lambda 表达式在成员方法中, this 指向当前类 输出: Value of i is: 10 this is point to ThisReferenceExample class