引用内部类的封闭实例 [英] Referencing an enclosing instance from an inner class

查看:298
本文介绍了引用内部类的封闭实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这只是一个知识/好奇心问题。



在Java工作了几年之后,这只是让我感到震惊。

  class Foo {

class Bar {

Foo.this.doSomething();

}

}

当我看在 Foo.this ,我认为它是一个静态参考,显然不是这种情况。



我知道这是Java规范的一部分,但确切地说当你使用< Class> .this



这是它只是的东西吗?

解决方案

< blockquote>

我知道这是Java规范的一部分,但确切地说当你使用.this时会发生什么?


它只是指 Bar 中的隐藏字段。通过反编译最容易看到这一点。你会看到有一个 Bar 构造函数,它引用了一个 Foo 的实例。该引用存储在一个字段中,然后当你使用 Foo.this 时,它只是访问该字段。假设您将 Foo.this.doSomething()放入 someMethod 调用,您的代码类似于:

  class Foo {

static class Bar {
private final Foo $ foo;

Bar(Foo foo){
this。$ foo = foo;
}

public void someMethod(){
$ foo.doSomething();
}
}
}


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?

解决方案

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

这篇关于引用内部类的封闭实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆