【问题标题】:How can "this" of the outer class be accessed from an inner class?如何从内部类访问外部类的“this”?
【发布时间】:2011-02-13 11:22:55
【问题描述】:

是否可以从 Java 内部类中获取对 this 的引用?

class Outer {

  void aMethod() {

    NewClass newClass = new NewClass() {
      void bMethod() {
        // How to I get access to "this" (pointing to outer) from here?
      }
    };
  }
}

【问题讨论】:

    标签: java inner-classes


    【解决方案1】:

    你可以像这样访问外部类的实例:

    Outer.this
    

    【讨论】:

      【解决方案2】:

      外部.this

      即。

      class Outer {
          void aMethod() {
              NewClass newClass = new NewClass() {
                  void bMethod() {
                      System.out.println( Outer.this.getClass().getName() ); // print Outer
                  }
              };
          }
      }
      

      顺便说一句,在 Java 中,类名按照约定以大写开头。

      【讨论】:

        【解决方案3】:

        将外部类的类名添加到此:

        outer.this
        

        【讨论】:

          【解决方案4】:

          是的,您可以在 this 中使用外部类名。 outer.this

          【讨论】:

            【解决方案5】:

            额外:当内部类被声明为“静态”时是不可能的。

            【讨论】:

              猜你喜欢
              • 2011-01-02
              • 2021-03-13
              • 2021-12-31
              • 2014-02-11
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-09-03
              相关资源
              最近更新 更多