简体   繁体   English

如何在java中访问匿名外部类的“this”引用

[英]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. 我想访问最内层类中的外部匿名类的“this”引用。 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() . 通常,如果在命名的外部类中有一个匿名嵌套类(让我们称之为“类外部”),他/她将在嵌套类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 在范围内无法访问Outer类型的封闭实例

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. 在实例化Inner对象之前,然后引用此变量。 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. 真正的目标是我想比较outerThisCopy的hashCodes和在new Inner对象(即Outer.this )中访问的对象以进行调试。 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] [上下文:参数是调用在“外部”类中实现的getter,它在“Inner”类中没有阴影,返回不同的对象]

Any ideas how do I access the "this" reference of the enclosing anonymous type ? 任何想法如何访问封闭匿名类型的“this”引用?

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();
            }
        };
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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