简体   繁体   中英

Anonymous inner class — getting “this”

I know that if I have an anonymous inner class and I need the outer class instance, I would just use Outer.this. However, I have an anon class within an anon class, and I want the instance of the latter (the outer anonymous class).

Example:

mRestService.getComicLatest(new Callback<Comic>() {

    @Override
    public void success(Comic comic, Response response) {
    }

    @Override
    public void failure(RetrofitError retrofitError) {
        mRetryFrame.findViewById(R.id.retry_button).setOnClickListener(
                new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mRestService.getComicLatest(WHAT_DO_I_PUT_HERE);
            }
        });
    }
});

In the above example, in the WHAT_DO_I_PUT_HERE, I want the instance of the Callback anon class.

Obviously, I know that I could just make an instance variable in the Callback class that holds a reference to "this" and use it for the WHAT_DO_I_PUT_HERE, but I was hoping there might be a cleaner way, much like how we call Outer.this for non-anon classes.

You could add a reference to this inside the outer anonymous class:

mRestService.getComicLatest(new Callback<Comic>() {

    private final Callback<Comic> outerAnon = this;

    @Override
    public void success(Comic comic, Response response) {
    }

    @Override
    public void failure(RetrofitError retrofitError) {
        mRetryFrame.findViewById(R.id.retry_button).setOnClickListener(
                new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mRestService.getComicLatest(outerAnon);
            }
        });
    }
});

You should be able to chain it further just like you started with Outer.this this should also work:

Outer.Inner.this

Edit: After reading further I see that I may have misunderstood your question, sorry if that is the case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM