[英]Access "this" from Java anonymous class
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.我想从我的匿名类的select()
方法中访问Container.select()
。 However, this.select()
would again call the anonymous class' select()
method.然而, this.select()
会再次调用匿名类的select()
方法。
My suggestion would be:我的建议是:
Introduce a field into Container, eg在容器中引入一个字段,例如
private Container self = this;
Now I can access Container.select()
by calling self.select()
from within the anonymous class.现在我可以通过从匿名类中调用self.select()
来访问Container.select()
。
Is this a reasonable way?这是一种合理的方式吗? Or are there any better ways?或者有什么更好的方法?
Container.this.select();
您可以编写Container.this.select()
以区别于内部类!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.