[英]Referring to non-final fields of an enclosing class inside an anonymous inner class in Java
In Java, I know that it is possible to do something like this: 在Java中,我知道可以这样做:
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. 这将在将来的某个时刻执行匿名Job
。 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. 在这种情况下,我的匿名Job
指的是封闭类的非final字段。 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? 作业运行时,我会看到greeting
字段的值,就像创建作业时的值,或者它在执行时的值? 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. 我想我知道答案,但我认为这是一个有趣的问题,起初它让我和几个同事再次猜测自己几分钟。
You'll see the value of greeting
as it is when the anonymous Job
executes. 当匿名Job
执行时,您将看到greeting
的值。
The final
modifier is required only for local variables, not member variables. final
修饰符仅对局部变量而非成员变量是必需的。
You are accessing the field through (the outer) this
). 您是通过(外)访问领域this
)。 You can think of this
as effectively a final
local variable. 您可以将this
视为final
局部变量。 Only the local is final
, the object pointed to is not (necessarily) constant. 只有本地是final
,指向的对象不一定(必然)。 Imagine a local variable with the same value as this
and it should be clear. 想象一下,用相同的值作为局部变量this
,它应该是清楚的。
public class Greeter {
private String greeting;
// ... Other methods that might mutate greeting ...
public void greetEventually() {
private final Greeter greeter = this; // <---
Job j = new Job() {
public void run() {
System.out.println( greeter.greeting ); // <---
}
};
j.schedule();
}
}
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; final修饰符仅应用于局部变量,以便为内部类的每个实例提供变量,因此我们使用:final String greeting;
When you need only one instance of the variable (like the case of constants or common resources), use: private String greeting; 当您只需要变量的一个实例时(如常量或公共资源的情况),请使用:private String greeting;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.