Java中最终局部变量的范围 [英] Scope of final local variable in java

查看:101
本文介绍了Java中最终局部变量的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Method-Local内部类无法访问局部变量,因为方法结束后,method-local内部类的实例可能仍然存在.但是,一旦局部方法结束,局部变量将消失. 我了解到方法本地内部类可以访问最终本地变量,这是否意味着方法结束后最终本地变量仍然有效?

Method-Local inner class cannot access local variables because the instance of the method-local inner class may still alive after the method is over. But local variables will vanish once the local method is over. I learned that method-local inner class can access final local variable, does this mean final local variable still alive after the method is over?

推荐答案

排序. Java匿名内部类的行为类似于关闭",也就是说,它们在当前本地状态周围关闭".但是,Java只允许这些类在最终变量周围关闭.如果没有更改,则变量的本地状态可能会更改,但是内部类中保存的版本不会更改,因此它将访问过期"实例.这可能会使程序员感到困惑.

Sort of. Java anonymous inner classes act like "closures," that is, they "close" around the current local state. However, Java only lets these classes close around final variables. If it didn't, the local state of the variable could change, but the version held in the inner class would not, so it would be accessing an "out of date" instance. This could be confusing to a programmer.

相反,Java要求实例通过方法而不是变量重新分配来处理可变性.这样可以提高清晰度,并允许更简单的调试.有关Java为什么执行此操作的更多信息,请参见此答案.

Instead, Java requires that mutability be handled by the instance through methods, not variable reassignment. This leads to better clarity and allows for simpler debugging. For more information about why Java does this, see this answer.

由于该类仍然持有对该变量的引用,因此您的问题的答案是,因此在内部类放弃该变量的所有权之前,该实例将不会被垃圾回收.

Since the class still holds a reference to the variable, the answer to your question is yes, that instance will not be garbage collected until the inner class relinquishes ownership of the variable.

这篇关于Java中最终局部变量的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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