java:为什么局部变量应该声明为final
可能的重复:
声明方法是否有任何性能原因Java 中的最终参数?
为什么要标记局部变量Java 中方法参数为“final”?
我正在使用 PMD 来查看代码违规。
在 webService 方法中,我有下面的代码
public ServiceRequest getData()
{
Status status = new Status();
// code
}
PMD 建议我的是,这个局部变量状态可以声明为最终状态。
我的问题是,将其定为最终版本会带来任何性能改进,或者如果不是的话,代码可以获得什么好处?
Possible Duplicate:
Is there any performance reason to declare method parameters final in Java?
Why would one mark local variables and method parameters as “final” in Java?
I am using PMD to see the code violations.
Inside a webService Method, I have this below code
public ServiceRequest getData()
{
Status status = new Status();
// code
}
What PMD is suggesting me is that, this local variable status could be declared as final.
My question is, making it final would result in any performance improvements or if not what benefits the code could get?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
摘自以下文章: http://www.javapractices.com/topic/ TopicAction.do?Id=23
这个问题也讨论了这一点: 可以过度使用最终伤害多于好处?
Taken from the following article: http://www.javapractices.com/topic/TopicAction.do?Id=23
This is also discussed in this question: Can excessive use of final hurt more than do good?
final
表示局部变量不会被改变。我的感觉是方法应该很短,您应该能够轻松理解它们,因此将变量设置为最终可能有点多余。我更喜欢将字段设置为
final
,因为使整个类如此短,是一个严重的限制。此外,字段可能存在线程安全问题,而局部变量则不会。final
indicates the local variable won't be changed. My feeling is that methods should be so short you should be able to easily understand them and so making the variable final may be a bit redundant.I prefer to make fields
final
because making the whole class so short, is a serious limitation. Also fields can have thread safety issues which local variables do not.我不知道将状态设置为最终状态会带来什么性能优势,但 PMD 建议您这样做,因为您可能永远不会在状态首次初始化后对其进行写入。
因此,通过将其设为最终版本,您所获得的只是您的代码更不容易出错 - 如果您将其声明为最终版本,则不能错误地覆盖它......
I dont know about performance-benefits by making status final, but PMD is suggesting you this, because probably you are never writing on status after its first initialization.
So what you gain by making it final is just that your code is less error-prone - if you declare it final, you cant overwrite it by mistake...