从Java匿名类访问“ this”


143

给出以下代码:

public interface Selectable {
  public void select();
}

public class Container implements Selectable {
  public void select() {
  ...
  }
  public void createAnonymousClass() {
    Selectable s = new Selectable() {
      public void select() {
        //see comment below.
      }
    };
  }
}

我想Container.select()从我的匿名类select()方法中访问。但是,this.select()将再次调用匿名类的select()方法。

我的建议是:

将字段引入到Container中,例如

private Container self = this;

现在,我可以Container.select()通过self.select()从匿名类中调用来访问。

这是合理的方法吗?还是有更好的方法?

Answers:



By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.