Consider this case:
public class SomeClass {
public void someMethod() {
new SomeInterface() {
public void someOtherMethod() {
new SomeOtherInterface() {
new someThirdMethod() {
//My question is about code located here.
}
};
}
};
}
}
Is there a syntax to reference the instance of the anonymous inner class represented by SomeInterface at the commented code? For SomeClass you can do SomeClass.this
Is there an equivalent to get the implementation of SomeInterface?
If not, of course you can just define a final local variable in the SomeInterface implementation and reference it, but I was just wondering if there is in fact direct language support to reference the instance.
The reason why SomeInterface.this
doesn't compile is because the enclosing class is not SomeInterface
, but rather some anonymous type.
You can't use qualified this
with anonymous type. That's why they're anonymous; you can't refer to them by name, and qualified this
works by explicitly naming an enclosing type.
It's tempting to try something like:
SomeClass$1.this
But then you get an error SomeClass$1 cannot be resolved to a type
; despite the fact that if you let this code compile without this line, it will (in all likelihood) create a SomeClass$1.class
.
You can either use a non-anonymous class and use qualified this
, or you can use the final
local variable technique you mentioned.
this
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