Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

java - Referencing an enclosing instance from an inner class

This is a knowledge/curiosity question only.

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

class Foo {

   class Bar{

      Foo.this.doSomething();

   }

}

When I look at Foo.this, I would assume that it's a static reference which obviously is not the case.

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

Is it one of those "it just is" things?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...