Getting hold of the outer class object from the inner class object

前端 未结 8 1385
孤独总比滥情好
孤独总比滥情好 2020-11-22 02:26

I have the following code. I want to get hold of the outer class object using which I created the inner class object inner. How can I do it?

pub         


        
8条回答
  •  旧时难觅i
    2020-11-22 02:52

    Within the inner class itself, you can use OuterClass.this. This expression, which allows to refer to any lexically enclosing instance, is described in the JLS as Qualified this.

    I don't think there's a way to get the instance from outside the code of the inner class though. Of course, you can always introduce your own property:

    public OuterClass getOuter() {
        return OuterClass.this;
    }
    

    EDIT: By experimentation, it looks like the field holding the reference to the outer class has package level access - at least with the JDK I'm using.

    EDIT: The name used (this$0) is actually valid in Java, although the JLS discourages its use:

    The $ character should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.

提交回复
热议问题