Accessing the containing class of an inner class in Java

六月ゝ 毕业季﹏ 提交于 2019-12-01 15:46:38
polygenelubricants

You can use what is called the qualified this.

JLS 15.8.4. Qualified This

Any lexically enclosing instance can be referred to by explicitly qualifying the keyword this.

Let C be the class denoted by ClassName. Let n be an integer such that C is the n-th lexically enclosing class of the class in which the qualified this expression appears. The value of an expression of the form ClassName.this is the n-th lexically enclosing instance of this (§8.1.3). The type of the expression is C. It is a compile-time error if the current class is not an inner class of class C or C itself.

In this case, you can do what Martijn suggests, and use:

workWithWidget(SearchWidget.this);

References

Related questions

You can write the name of the outer class and then .this. So:

workWithWidget(SearchWidget.this);

To access super of the object that contains an object of an anonymous class from that object, try, in your case SearchWidget.super


Example:(see the third call Child.super.print())

public class Test1 {
public static void main(String[] args) {
    new Child().doOperation();
}
}

class Parent {
protected void print() {
    System.out.println("parent");
}
}

class Child extends Parent {
@Override
protected void print() {
    super.print();
    System.out.println("child");
}

void doOperation() {
    new Runnable() {
        public void run() {
            print();              // prints parent child
            Child.this.print();   // prints parent child
            Child.super.print();  // prints parent
        }
    }.run();

}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!