问题
As I understand it, any variables used within an inner anonymous class (but declared outside of it) are actually passed a copy of their values. There is also a requirement that these outer variables be declared as final, which obviously means that these variables are not meant to be modified.
But is there any kind of work-around to this? Can my anonymous inner class actually modify some variable or object, which I could then use later on in my code (outside of the anonymous class)? Or would the modifications not be seen outside of the anonymous class?
回答1:
The behavior you are referring to applies only to local variables or method/catch parameters. You can access and, potentially, modify instance members just fine
public class Example {
public void method() {
String localFoo = "local";
new Object() {
public void bar() {
foo = "bar"; // yup
System.out.println(localFoo); // sure
localFoo = "bar"; // nope
}
};
}
private String foo = "foo";
}
The anonymous Object inner class copies the value of localFoo for use within the println(..) invocation. However, for foo, it's actually "copying" the reference to the Example instance and referencing its foo field.
It's actually equivalent to
Example.this.foo = "bar";
回答2:
Referenced objects do indeed need to be final - however, they can be mutable.
class Holder<T> {
public T held;
}
public void test() {
final Holder<String> s = new Holder<>();
new Runnable () {
@Override
public void run() {
s.held = "Hello;";
}
}
}
This is greatly simplified - you would normally use getters and setters for the held value.
来源:https://stackoverflow.com/questions/27661649/modifying-an-outer-variable-within-an-anonymous-inner-class