为什么我们对匿名内部类使用final关键字?
我目前正在与 Sierra & 一起准备 S(O)CJP。贝茨的书。
关于内部类(方法局部或匿名),他们说我们无法访问局部变量,因为它们位于堆栈上,而类位于堆上并且可以由方法返回,然后尝试访问这些变量那些在堆栈上但由于方法结束而不再存在的...
众所周知,我们可以通过使用final关键字来绕过这个。这是他们在书中所说的,但他们并没有真正解释最终关键字的效果是什么...... 据我所知,在方法局部变量上使用final关键字并不会让它存在于堆上......那么该类如何能够访问仍然存在于堆栈上的final变量,而可能没有更多堆栈???
我想内部类中应该有这个最终局部变量的某种“副本”。既然值不能改变,为什么不复制这些信息...... 有人可以确认这一点或告诉我我是否遗漏了什么吗?
I'm currently preparing the S(O)CJP, with the Sierra & Bates book.
About inner classes (method local or anonymous), they say that we can't access the local variables because they live on the stack while the class lives on the heap and could get returned by the method and then try to have access to these variables that are on the stack but do not exist anymore since the method has ended...
As we all know, we can bypass this by using the final keyword. This is what they say in the book but they don't really explain what's the effect of that final keyword...
As far as i know, using the final keyword on a method local variable doesn't make it live on the heap... So how would the class be able to access a final variable that still lives on the stack while there could be no more stack???
I guess there should be some kind of "copy" of this final local variable inside the inner class. Since the value can't change, why not duplicating this information...
Can someone confirm this or tell me if i'm missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的直觉是正确的,因为该变量是最终的,因此可以安全地复制它。当然,对于引用类型,这意味着将引用复制到对象而不是它所引用的对象。
Your intuition is correct, because the variable is final it is safe to make a copy of it. Of course for reference types this means copying the reference to the object and not the object it refers to.
编译器使用微妙的技巧在幕后复制最终引用,让内部类到达外部类中的最终字段。复制是字段必须是最终字段的原因,这样值就不会改变。
参见例如 http:// tech-read.com/2008/06/19/why-inner-class-can-access-only-final-variable/
The compiler uses subtle trickery copying the final reference under the covers to let the inner class get to the final field in the outer class. The copying is why the field must be final so the value does not change.
See e.g. http://tech-read.com/2008/06/19/why-inner-class-can-access-only-final-variable/