为什么不能将方法的局部变量声明为final?
我想知道为什么方法的本地变量不能声明为最终变量。 有什么具体原因吗?
这是否意味着Java中没有局部常量?
I like to know why Variables that are local to a method cannot be declared final.
Is there any specific reason?
Does it mean are there no local constants in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它们可以被宣布为最终的。你的实际问题出在其他地方。
They can be declared final. Your actual problem lies somewhere else.
来自 Java 规范 §4.5.4 :
换句话说,这是完全合法的。此外,使用
final 被认为是最佳实践
尽可能使用局部变量。From the Java specification §4.5.4:
In other words, it is perfectly legal. Moreover, it is considered a best practice to use
final
with local variables as much as possible.谁说我们不能。我们可以声明。您可能对不能在方法中使用的 static 感到困惑。
who said we cannot. we can declare. You might have confused with static which cannot be used in methods.
愚蠢的错误!可能您错过了提及引用变量,并且 Eclipse 会抱怨“令牌“final”上的语法错误,无效类型”。
示例
final Pojo = new Pojo();
缺少引用变量,但如果final Pojo pojo = new Pojo();
则可以完美工作我确信当你在 SO 提出问题时,你并没有意识到那里存在那个愚蠢的错误。
Silly mistake! Probably you missed mentioning the reference variable and eclipse complains like 'Syntax error on token "final", invalid Type'.
Example
final Pojo = new Pojo();
which has missing reference variable while it perfectly works iffinal Pojo pojo = new Pojo();
I am sure when you asked question here at SO by that time you didn't realize that silly mistake there.