I have a situation where I need to grab a reference to an enclosing anonymous inner class:
I have some asynchronous method doSomething(...)
that calls a result-callback when it's done (given to me by a library; can't change this) and I'm trying to write a result-callback that automatically retries the doSomething(...)
call a couple of times if it fails by posting a Runnable
to a message queue that gets executed after a 100-ms retry-delay.
Since that call needs to again pass in the same result-callback, I need to get a reference to my result-callback from within the Runnable
's run-method like so:
interface ResultListener {
public void onSuccess();
public void onFailure();
}
private static void doSomething(ResultListener listener) {
// Do something fun here...
}
public static void main(String[] args) throws IOException {
final ResultListener autoRetry = new ResultListener() {
@Override
public void onSuccess() {
// Yay! Everything works!
}
@Override
public void onFailure() {
final ResultListener outerThis = this; // This can't be necessary!
// Schedule retry in 100ms
messageThread.postDelayed(new Runnable() {
@Override
public void run() {
doSomething(outerThis); // What else could I do here?
}
}, 100);
}
};
doSomething(autoRetry);
}
Is using this outerThis
-hack the only way to do this? It seems really clunky. The following don't work:
this
- returns the instance ofRunnable
, not the anonymousResultListener
ResultListener.this
(which I would have expected to work) throwsNo enclosing instance of the type ResultListener is accessible in scope
autoRetry
throwsThe local variable autoRetry may not have been initialized
Clearly, I could just name the anonymous class by defining a RetryListener
class, which I then instantiate instead and use RetryListener.this
, but this again seems like it shouldn't be necessary...
Am I missing something?