java:为什么Local变量应该声明为final [英] java :Why the Local variable should be declared final

查看:164
本文介绍了java:为什么Local变量应该声明为final的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在Java中声明方法参数是否有任何性能原因?

为什么将局部变量和方法参数标记为最终&rdquo ;在Java?

我正在使用PMD来查看违规行为。

I am using PMD to see the code violations.

在webService方法中,我有以下代码

Inside a webService Method, I have this below code

public ServiceRequest getData()
{
Status status = new Status();
// code
}

PMD建议我的是,这个本地变量状态可以声明为final。

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?

推荐答案

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.

我更喜欢制作字段 final 因为全班这么短,是一个严重的限制。字段也可能存在线程安全问题,而局部变量则没有。

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.

这篇关于java:为什么Local变量应该声明为final的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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