Chloe Chloe - 2 months ago 13
Java Question

Two double nested anonymous inner classes. How to get 1st level anonymous class members?

Inner class is Adapter, inner-inner class is Listener. How to access (obscured) Adapter members/methods from Listener?

list.setAdapter(new Adapter() {
public View getView() {
// ...
button.setListener(new Listener() {
public void onClick() {
Adapter.this.remove(item);
}
);
}
});


Normally to access the outer classes members, you just say Outer.this.member, but in this case it gave me the following error (using the actual class):

error: not an enclosing class: ArrayAdapter


So how are you supposed to access an inner class members from an inner-inner class? I don't like multi-level nested anonymous classes, but in this case I'm learning a new API and am not sure of a cleaner way yet. I already have a workaround but wanted to know anyways. remove() isn't really obscured by the inner-inner class so specifying the class isn't really necessary in this case, but wanted to make it clear in the code exactly where this remove() method is. I also wanted to know in case it is obscured. I believe using
Outer.$6.remove()
would work, but I don't believe it should be that way either.

Answer

Assign this to a variable, then access that one of innermost class.

list.setAdapter(new Adapter() {
  public View getView() {
    final Adapter that = this;
    button.setListener(new Listener() {
      public void onClick() {
        that.remove(item);
      }
    );
  }
});

I'm not sure what would be a good naming here. Perhaps adapter?