How to refer to enclosing anonymous class instance in Java?

妖精的绣舞 提交于 2019-12-10 20:44:57

问题


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()
    }
});

回答1:


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()
    }
});


来源:https://stackoverflow.com/questions/28784624/how-to-refer-to-enclosing-anonymous-class-instance-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!