简体   繁体   中英

How to access “this” reference of anonymous outer class in java

I have the following problem. Two nested anonymous types. I want to access "this" reference of the outer anonymous class inside the most inner class. Usually if one has anonymous nested class in a named outer class (lets call it "class Outer") he/she would type inside the nested class Outer.this.someMethod() . How do I refer the outer class if it's anonymous ? Example Code:

public interface Outer {
    void outerMethod();
}

public interface Inner {
    void innerMethod();
}
...
public static void main(String[] args) {
...
new Outer() {
    public void outerMethod() {
        new Inner() {
            public void innerMethod() {
                Outer.this.hashCode(); // this does not work
            } // innerMethod
        }; // Inner
    } // outerMethod
}; // Outer
...
} // main

The error I get is

No enclosing instance of the type Outer is accessible in scope

I know that I can copy the reference like this:

final Outer outerThisCopy = this;

just before instantiating the Inner object and then refer to this variable. The real goal is that I want to compare the hashCodes of outerThisCopy and the object accessed inside the new Inner object (ie the Outer.this ) for debugging purposes. I have some good arguments to think that this two objects are different (in my case). [Context: The argument is that calling a getter implemented in the "Outer" class which is not shadowed in the "Inner" class returns different objects]

Any ideas how do I access the "this" reference of the enclosing anonymous type ?

Thank you.

You cannot access an instance of anonymous class directly from inner class or another anonymous class inside it, since the anonymous class doesn't have a name. However, you can get a reference to the outer class via a method:

new Outer()
{
    public Outer getOuter()
    {
        return this;
    }

    public void outerMethod()
    {
        new Inner()
        {
            public void innerMethod()
            {
                getOuter().hashCode();
            }
        };
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM