"Why are you doing this what is wrong with you?" notwithstanding, is there any way to accomplish this without changing the final method parameter name?
private Foo createAnonymousFoo(final Bar bar) {
return new Foo() {
private Bar bar = SomeUnknownScopeQualifier.bar;
public Bar getBar() {
return bar;
}
public void doSomethingThatReassignsBar() {
bar = bar.createSomeDerivedInstanceOfBar();
}
};
}
Obviously without the doSomethingThatReassignsBar call, you wouldn't need the member Bar and so on. In this case, the simple fix is to change final Bar bar
to something like final Bar startBar
and then the assignment is fine. But out of curiosity, is it possible to specifically refer to the final Bar
(Similar to the way you would say Super.this
)?
An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final. Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing scope that have the same name.
The final keyword when used for parameters/variables in Java marks the reference as final. In case of passing an object to another method, the system creates a copy of the reference variable and passes it to the method. By marking the new references final, you protect them from reassignment.
I think the answer to your question is "no". From the Java Language Specification:
A local variable (§14.4), formal parameter (§8.4.1), exception parameter (§14.20), and local class (§14.3) can only be referred to using a simple name (§6.2), not a qualified name (§6.6).
In other words, there's nothing you can replace SomeUnknownScopeQualifier
with in your example code to make the assignment statement in the inner class refer to the formal parameter name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With