gpt4 book ai didi

java - 为什么匿名类即使不需要也捕获 "this"?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:00:58 26 4
gpt4 key购买 nike

给定这段代码:

class Foo {}

public class Test {
public Foo makeFoo(String p, String q) {
return new Foo(){
public void doSomething() {
System.out.println(p);
}
};
}
}

当你编译它并运行 javap -c -p 'Test$1.class' 时,你会得到这个:

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
}

当创建匿名类时,变量 p 被捕获到 val$p (正如预期的那样,因为它是需要的),变量 q 不是(如预期的那样,因为不需要)。然而,Test.this 被捕获到 this$0 中,即使它不是必需的。这是 Java 规范强制要求的,还是恰好是它的工作方式?为什么会这样?

最佳答案

因为是内部类,又因为

An instance i of a direct inner class C of a class or interface O is associated with an instance of O, known as the immediately enclosing instance of i. The immediately enclosing instance of an object, if any, is determined when the object is created (§15.9.2).

JLS 8.1.3 .

“即使他们不需要”也不异常(exception)。

关于java - 为什么匿名类即使不需要也捕获 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48106601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com