Java – why do anonymous classes catch “this” even if they don’t need it?
•
Java
In view of this Code:
class Foo {} public class Test { public Foo makeFoo(String p,String q) { return new Foo(){ public void doSomething() { System.out.println(p); } }; } }
When you compile and run javap - C - p 'test $1 Class', you get this:
Compiled from "Test.java" class Test$1 extends Foo { final java.lang.String val$p; final Test this$0; Test$1(Test,java.lang.String); Code: 0: aload_0 1: aload_1 2: putfield #1 // Field this$0:LTest; 5: aload_0 6: aload_2 7: putfield #2 // Field val$p:Ljava/lang/String; 10: aload_0 11: invokespecial #3 // Method Foo."<init>":()V 14: return public void doSomething(); Code: 0: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream; 3: aload_0 4: getfield #2 // Field val$p:Ljava/lang/String; 7: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 10: return }
When an anonymous class is created, the variable p is captured in Val $p (as expected, because it is required), and the variable Q is not (as expected, because it is not required) But, test This is captured to this $0, even if it is not required Is this a mandatory requirement of the Java specification, or does it just work? Why do you work like this?
Solution
Because it is an intrinsic class, because
JLS 8.1. three
"Even if they don't need it" is no exception
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码