java - 从嵌套内部类访问外部内部类

标签 java inner-classes anonymous-class anonymous-inner-class

我有以下代码:

public class Bar {}
public class FooBar {}

public class Foo {

    public void method() {
        new Bar() {

            void otherMethod() { }

            void barMethod() {

                new FooBar() {

                    void fooBarMethod() {
                        Bar.this.otherMethod(); // not compiles
                    }   
                };
            }
        };
    }

}

所以我有一个匿名内部类,其中有另一个匿名内部类。问题:有没有办法从内部类 FooBar 访问外部内部类 Bar 的方法?

最佳答案

您可以使用简单名称直接调用该方法:

void fooBarMethod() {
    otherMethod(); // compiles
}

当您在 new FooBar() 匿名类中定义另一个名为 otherMethod() 的方法时,这将失败。

Bar.this 不会真正起作用,因为那里是一个匿名类,其名称在编译时给出。它将获得类似 Foo$1 的名称。所以,不,你不能有类似 Bar.this 的东西。


好的,我写了这个源文件:

class Bar { }

class FooBar { }

public class Demo {

    public static void main() {
        new Demo().method();
    }

    public void method() {
        new Bar() {

            void otherMethod() { System.out.println("Hello"); }

            void barMethod() {

                new FooBar() {

                    void fooBarMethod() {
                        otherMethod(); // not compiles
                    }   
                }.fooBarMethod();
            }
        }.barMethod();
    }
}

生成的类文件是:

Bar.class
FooBar.class
Demo.class

Demo$1.class    // For `new Bar()` anonymous class
Demo$1$1.class  // For `new FooBar()` anonymous class

现在,让我们直接看new FooBar()匿名类的字节码。该类将被命名为 - Demo$1$1。所以,运行 javap 命令,我得到了这个输出:

class Demo$1$1 extends FooBar {
  final Demo$1 this$1;

  Demo$1$1(Demo$1);
    Code:
       0: aload_0
       1: aload_1
       2: putfield      #1                  // Field this$1:LDemo$1;
       5: aload_0
       6: invokespecial #2                  // Method FooBar."<init>":()V
       9: return

  void fooBarMethod();
    Code:
       0: aload_0
       1: getfield      #1                  // Field this$1:LDemo$1;
       4: invokevirtual #3                  // Method Demo$1.otherMethod:()V
       7: return
}

final 字段有一个对 new Bar() 实例的引用副本。因此,otherMethod() 是在 this$1 引用上调用的,它是对 new Bar() 匿名内部类实例的引用。好吧,您只是想这样做,但由于这是一个匿名内部类,您不能直接访问 this 引用。但是,这是隐含的。


更详细的分析:

关于java - 从嵌套内部类访问外部内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21263022/

相关文章:

java - "parameterTypes"方法中 "java.lang.Class.getMethod()"的解释和正确格式

c++ - Visual Studio 2012 中的智能感知 : No members available for Inner classes in class template?

java - 在外部类和内部类之间,在外部类内部或外部调用 main 方法时,它们的静态初始化程序运行顺序不同

java - 实现内部匿名 Action 监听器

java - Java 中的闭包或类似的东西

Java:匿名类作为现有接口(interface)的子类?

java - Spring RestTemplate 实现与 RestOperations 接口(interface)

java - PrimeFaces 3.2 中的标签库

java - 页面无法加载,Apache Tomcat 服务器错误

java - 在java中替换字符串的有效方法