在 Java 中引用匿名内部类中封闭类的非最终字段
在Java中,我知道可以做这样的事情:
public class Greeter {
public void greetEventually() {
final String greeting = "Hello!";
Job j = new Job() {
public void run() {
System.out.println(greeting);
}
};
j.schedule();
}
}
这将在将来的某个时刻执行匿名Job
。这是可行的,因为匿名类可以引用封闭范围内的最终变量。
我不确定的是以下情况:
public class Greeter {
private String greeting;
// ... Other methods that might mutate greeting ...
public void greetEventually() {
Job j = new Job() {
public void run() {
System.out.println(greeting);
}
};
j.schedule();
}
}
在这种情况下,我的匿名 Job 引用了封闭类的非最终字段。当作业运行时,我会看到创建作业时的欢迎字段值还是执行作业时的值吗?我想我知道答案,但我认为这是一个有趣的问题,起初它让我和几个同事对自己进行了几分钟的反思。
In Java, I know that it is possible to do something like this:
public class Greeter {
public void greetEventually() {
final String greeting = "Hello!";
Job j = new Job() {
public void run() {
System.out.println(greeting);
}
};
j.schedule();
}
}
This would execute the anonymous Job
at some point in the future. This works because anonymous classes are allowed to refer to final variables in the enclosing scope.
What I'm not sure about is the following case:
public class Greeter {
private String greeting;
// ... Other methods that might mutate greeting ...
public void greetEventually() {
Job j = new Job() {
public void run() {
System.out.println(greeting);
}
};
j.schedule();
}
}
In this case my anonymous Job
is referring to a non-final field of the enclosing class. When the Job runs, will I see the value of the greeting
field as it was when the Job was created, or as it is when it is executing? I think I know the answer, but I thought it was an interesting question, and at first it left me and a couple of coworkers second-guessing ourselves for a few minutes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将看到执行匿名
Job
时greeting
的值。仅局部变量需要
final
修饰符,成员变量不需要。You'll see the value of
greeting
as it is when the anonymousJob
executes.The
final
modifier is required only for local variables, not member variables.您正在通过(外部)
this
访问该字段。您可以将this
实际上视为一个final
局部变量。只有本地是final
,指向的对象不是(必然)常量。想象一个与this
具有相同值的局部变量,它应该很清楚。You are accessing the field through (the outer)
this
). You can think ofthis
as effectively afinal
local variable. Only the local isfinal
, the object pointed to is not (necessarily) constant. Imagine a local variable with the same value asthis
and it should be clear.Final修饰符应用于局部变量只是为了为内部类的每个实例提供变量,因此我们使用:
最后的字符串问候语;
当您只需要变量的一个实例时(例如常量或公共资源的情况),请使用:
私人字符串问候语;
The final modifier is applied to the local variables only to provide variables for each instance of the inner class, so we use:
final String greeting;
When you need only one instance of the variable (like the case of constants or common resources), use:
private String greeting;