从 Java 匿名类访问“this”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1084112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:23:38  来源:igfitidea点击:

Access "this" from Java anonymous class

javathisanonymous-class

提问by Bob

Given the following code:

鉴于以下代码:

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.
      }
    };
  }
}

I want to access Container.select()from within my anonymous class' select()method. However, this.select()would again call the anonymous class' select()method.

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

My suggestion would be:

我的建议是:

Introduce a field into Container, e.g.

在容器中引入一个字段,例如

private Container self = this;

Now I can access Container.select()by calling self.select()from within the anonymous class.

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

Is this a reasonable way? Or are there any better ways?

这是一种合理的方式吗?或者有什么更好的方法?

采纳答案by Mykola Golubyev

Container.this.select();

回答by PeterMmm

You can write Container.this.select()to distinct from the inner class !

你可以写Container.this.select()区别于内部类!