Referencing an enclosing instance from an inner class

后端 未结 1 1444
半阙折子戏
半阙折子戏 2020-12-16 07:06

This is a knowledge/curiosity question only.

After several years in Java, this has only just struck me.

class Foo {

   class Bar{

      Foo.this.do         


        
相关标签:
1条回答
  • 2020-12-16 07:46

    I know this is part of the Java spec, but exactly what is going on when you use .this?

    It just refers to a "hidden" field within Bar. It's easiest to see this by decompiling. You'll see that there's a Bar constructor taking a reference to an instance of Foo. That reference is stored in a field, and then when you use Foo.this, it just accesses that field. So assuming you'd put your Foo.this.doSomething() into a someMethod call, your code is similar to:

    class Foo {
    
       static class Bar {
          private final Foo $foo;
    
          Bar(Foo foo) {
              this.$foo = foo;
          }    
    
          public void someMethod() {
              $foo.doSomething();
          }
       }
    }
    
    0 讨论(0)
提交回复
热议问题