3

I'd like to know if it's possible (and how if it is) to refer to enclosing anonymous class instance in Java.

Example code:

final Handler handler = new Handler();

handler.post(new Runnable() {
    @Override
    public void run() {
        new Task() {
            @Override
            public void onTaskFinish() {
                handler.post(?); // what should go here?
            }
        }.execute()
    }
});
Aruziell
  • 243
  • 1
  • 8
  • `self`? [extra chars] – KSFT Feb 28 '15 at 17:25
  • According to this: http://stackoverflow.com/questions/18062961/access-outer-anonymous-class-from-inner-anonymous-class You must name/declare a new class and make an instance of it. – Shashank Feb 28 '15 at 17:28
  • I see. I was curious if there is something like `Runnable.this` that would be working for anonymous classes as well. – Aruziell Feb 28 '15 at 17:31

1 Answers1

4

If you were also a JavaScript coder, I bet you wouldn't need to ask this :) There is a trivial way to achieve what you want (and happens to be an important JavaScript idiom due to its peculiar semantics surrounding this).

handler.post(new Runnable() {
    @Override
    public void run() {
        final Runnable self = this;
        new Task() {
            @Override
            public void onTaskFinish() {
                handler.post(self);
            }
        }.execute()
    }
});
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • 1
    And this is exactly what I did! I was just curious if it could be achieved from inside anonymous class derived from `Task`, but without outer reference. Since your code answers my question I accept your answer. – Aruziell Feb 28 '15 at 18:18