将 java 方法参数设置为最终参数
final
与下面的代码有什么区别。将参数声明为 final
有什么好处吗?
public String changeTimezone( Timestamp stamp, Timezone fTz, Timezone toTz){
return ....
}
public String changeTimezone(final Timestamp stamp, final Timezone fTz,
final Timezone toTz){
return ....
}
What difference that final
makes between the code below. Is there any advantage in declaring the arguments as final
.
public String changeTimezone( Timestamp stamp, Timezone fTz, Timezone toTz){
return ....
}
public String changeTimezone(final Timestamp stamp, final Timezone fTz,
final Timezone toTz){
return ....
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
由于形式方法参数是局部变量,因此只有将它们声明为 Final 时,才可以从内部匿名类访问它们。
这使您无需在方法主体中声明另一个局部最终变量:
As a formal method parameter is a local variable, you can access them from inner anonymous classes only if they are declared as final.
This saves you from declaring another local final variable in the method body:
摘自 最后一句话关于最终关键字
Extract from The final word on the final keyword
Final 阻止您为变量分配新值,这有助于捕获拼写错误。从风格上讲,您可能希望保持收到的参数不变并仅分配给局部变量,因此 Final 将有助于强制执行该风格。
必须承认我很少记得使用final 作为参数,也许我应该这样做。
The final prevents you from assigning a new value to the variable, and this can be helpful in catching typos. Stylistically you might like to keep the parameters received unchanged and assign only to local variables, so final would help to enforce that style.
Must admit I rarely remember to use final for parameters, maybe I should.
这并没有多大区别。它只是意味着你不能写:
但你仍然可以写:
这主要是向跟随你的维护程序员的提示,你不会在方法中间的某个地方为参数分配新值。并不明显,因此可能会引起混乱。
It doesn't make a lot of difference. It just means that you can't write:
but you can still write:
It's mainly a hint to the maintenance programmer that follows you that you aren't going to assign a new value to the parameter somewhere in the middle of your method where it isn't obvious and might therefore cause confusion.
在 Java 中用于参数/变量时,final 关键字将引用标记为 Final。如果将对象传递给另一个方法,系统会创建引用变量的副本并将其传递给该方法。通过将新参考标记为最终参考,可以保护它们不被重新分配。有时这被认为是一种良好的编码实践。
The final keyword when used for parameters/variables in Java marks the reference as final. In case of passing an object to another method, the system creates a copy of the reference variable and passes it to the method. By marking the new references final, you protect them from reassignment. It's considered sometimes a good coding practice.
对于此方法的主体,
final
关键字将防止参数引用被意外重新分配,从而在这些情况下产生编译错误(大多数 IDE 会立即抱怨)。有些人可能会争辩说,只要有可能,一般使用final
会加快速度,但在最近的 JVM 中情况并非如此。For the body of this method the
final
keyword will prevent the argument references to be accidentally reassigned giving a compile error on those cases (most IDEs will complain straight away). Some may argue that usingfinal
in general whenever possible will speed things up but that's not the case in recent JVMs.列出了我看到的两个优点:
1 将方法参数标记为 Final 可以防止在方法内重新分配参数
从您的示例来看,
在复杂的方法中,将参数标记为 Final 将有助于意外解释这些参数作为方法局部变量并重新分配为编译器将标记这些情况,如示例所示。
2 将参数传递给匿名内部类
由于形式方法参数是局部变量,因此只有在将它们声明为final时,才可以从内部匿名类访问它们。
Two advantages that I see are listed :
1 Marking the method argument as final prevents reassignment of the argument inside the method
From you example
In a complicated method marking the arguments as final will help in accidental interpretation of these arguments as methods local variables and reassigning as compiler will flag these cases as shown in the example.
2 Passing the argument to an anonymous inner class
As a formal method parameter is a local variable, you can access them from inner anonymous classes only if they are declared as final.
我所说的是一般来说将变量和字段标记为final - 不仅仅适用于方法参数。 (将方法/类标记为final是完全不同的事情)。
这对代码的读者/未来维护者来说是一个好处。与变量的合理名称一起,可以让代码的读者看到/理解所讨论的变量所代表的内容,这会很有帮助并且让他们放心,并且让读者放心的是,每当您在同一范围内看到该变量时,其含义仍然存在同样的,所以他(她)不必绞尽脑汁去弄清楚变量在每个上下文中的含义。我们已经看到了太多对变量“重用”的滥用,这使得即使是很短的代码片段也难以理解。
I'm speaking of marking variables and fields final in general - doesn't just apply to method arguments. (Marking methods/classes final is a whole different thing).
It's a favor to the readers/future maintainers of your code. Together with a sensible name of the variable, it's helpful and reassuring to the reader of your code to see/understand what the variables in question represent - and it's reassuring to the reader that whenever you see the variable in the same scope, the meaning stays the same, so (s)he doesn't have to scratch his head to always figure out what a variable means in every context. We've seen too many abuses of "re-use" of variables, that makes even a short code snippet hard to understand.
它只是 Java 中的一个构造,可以帮助您定义契约并遵守它。这里有类似的讨论: http://c2.com/cgi/wiki?JavaFinalConsideredEvil
顺便说一句 - (正如 twiki 所说),如果您遵循良好的编程原则并且完成了重新分配/重新定义传入参数引用,则将 args 标记为 Final 通常是多余的。
在最坏的情况下,如果您重新定义 args 引用,它不会影响传递给函数的实际值 - 因为只传递了一个引用。
Its just a construct in Java to help you define a contract and stick to it. A similar discussion here : http://c2.com/cgi/wiki?JavaFinalConsideredEvil
BTW - (as the twiki says), marking args as final is generally redundant if you are following good programming principles and hance done reassign / redefine the incoming argument reference.
In the worst case, if you do redefine the args reference, its not going to affect the actual value passed to the function - since only a reference was passed.
- 过去(Java 8 之前:-) )
显式使用“final”关键字会影响内部匿名类的方法变量的可访问性。
- 在现代(Java 8+)语言中,不需要这样的用法:
Java 引入了“有效的最终”变量。如果代码不暗示变量值的更改,则局部变量和方法参数被假定为最终的。因此,如果您在 Java8+ 中看到这样的关键字,您可以认为它是不必要的。 “有效最终”的引入使我们在使用 lambda 时键入更少的代码。
- In the past (before Java 8 :-) )
Explit use of "final" keyword affected accessibility of the method variable for internal anonymous classes.
- In modern (Java 8+) lanaguage there is no need for such usage:
Java introduced "effectively final" variables. Local variables and method paramters are assummed final if the code does not imply changing of value of the variable. So if you see such keyword in Java8+ you can assume it is unecessary. Introduction of "effectively final" makes us type less code when using lambdas.
Final 关键字可防止您为参数分配新值。我想用一个简单的例子来解释这一点
假设我们有一个方法
情况下,如果在 method2 中为“dateOfBirth”分配了新值,则会导致 method3 的输出错误。因为传递给 method3 的值不是传递给 method2 之前的值。因此要避免将final关键字用于参数。
这也是 Java 编码最佳实践之一。
The final keyword prevents you from assigning a new value to the parameter. I would like to explain this with a simple example
Suppose we have a method
In the above case if the "dateOfBirth" is assigned new value in method2 than this would result in the wrong output from method3. As the value that is being passed to method3 is not what it was before being passed to method2. So to avoid this final keyword is used for parameters.
And this is also one of the Java Coding Best Practices.