Accessing the containing class of an inner class in Java

后端 未结 3 999
时光取名叫无心
时光取名叫无心 2021-01-17 09:12

This is what I\'m doing now. Is there a better way to access the super class?

public class SearchWidget {
    private void addWishlistButton() {
        fina         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-17 09:32

    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

    • JLS 15.8.4. Qualified This
    • JLS 8.1.3 Inner Classes and Enclosing Instances

    Related questions

    • Access outer class from inner class: Why is it done this way?

提交回复
热议问题