将 java 方法参数设置为最终参数

发布于 2024-10-02 05:55:31 字数 316 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

寂寞美少年 2024-10-09 05:55:31

由于形式方法参数是局部变量,因此只有将它们声明为 Final 时,才可以从内部匿名类访问它们。

这使您无需在方法主体中声明另一个局部最终变量:

 void m(final int param) {
        new Thread(new Runnable() {
            public void run() {
                System.err.println(param);
            }
        }).start();
    }

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:

 void m(final int param) {
        new Thread(new Runnable() {
            public void run() {
                System.err.println(param);
            }
        }).start();
    }
难得心□动 2024-10-09 05:55:31

摘自 最后一句话关于最终关键字

最终参数

以下示例声明最终参数:

public void doSomething(final int i, final int j)
{
  // cannot change the value of i or j here...
  // any change would be visible only inside the method...
}

这里使用final来保证两者
索引 i 和 j 不会意外地出现
通过方法重置。这是一个方便的方法
防止潜在的错误
错误地改变了值
你的参数。一般来说,
简短的方法是更好的方法
防止此类错误的发生,但是
最终参数可能很有用
除了您的编码风格之外。

请注意,最终参数不是
被视为该方法的一部分
签名,并被忽略
编译器在解析方法调用时。
参数可以声明为最终的(或
不)不影响如何
方法被重写。

Extract from The final word on the final keyword

Final Parameters

The following sample declares final parameters:

public void doSomething(final int i, final int j)
{
  // cannot change the value of i or j here...
  // any change would be visible only inside the method...
}

final is used here to ensure the two
indexes i and j won't accidentally be
reset by the method. It's a handy way
to protect against an insidious bug
that erroneously changes the value of
your parameters. Generally speaking,
short methods are a better way to
protect from this class of errors, but
final parameters can be a useful
addition to your coding style.

Note that final parameters are not
considered part of the method
signature, and are ignored by the
compiler when resolving method calls.
Parameters can be declared final (or
not) with no influence on how the
method is overriden.

鸠魁 2024-10-09 05:55:31

Final 阻止您为变量分配新值,这有助于捕获拼写错误。从风格上讲,您可能希望保持收到的参数不变并仅分配给局部变量,因此 Final 将有助于强制执行该风格。

必须承认我很少记得使用final 作为参数,也许我应该这样做。

public int example(final int basicRate){
    int discountRate;

    discountRate = basicRate - 10;
    // ... lots of code here 
    if ( isGoldCustomer ) {
        basicRate--;  // typo, we intended to say discountRate--, final catches this
    }
    // ... more code here

    return discountRate;
}

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.

public int example(final int basicRate){
    int discountRate;

    discountRate = basicRate - 10;
    // ... lots of code here 
    if ( isGoldCustomer ) {
        basicRate--;  // typo, we intended to say discountRate--, final catches this
    }
    // ... more code here

    return discountRate;
}
骄傲 2024-10-09 05:55:31

这并没有多大区别。它只是意味着你不能写:

stamp = null;
fTz = new ...;

但你仍然可以写:

stamp.setXXX(...);
fTz.setXXX(...);

这主要是向跟随你的维护程序员的提示,你不会在方法中间的某个地方为参数分配新值。并不明显,因此可能会引起混乱。

It doesn't make a lot of difference. It just means that you can't write:

stamp = null;
fTz = new ...;

but you can still write:

stamp.setXXX(...);
fTz.setXXX(...);

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.

风蛊 2024-10-09 05:55:31

在 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.

帅的被狗咬 2024-10-09 05:55:31

对于此方法的主体,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 using final in general whenever possible will speed things up but that's not the case in recent JVMs.

友欢 2024-10-09 05:55:31

列出了我看到的两个优点:

1 将方法参数标记为 Final 可以防止在方法内重新分配参数

从您的示例来看,

    public String changeTimezone(final Timestamp stamp, final Timezone fTz, 
            final Timezone toTz){
    
    // THIS WILL CAUSE COMPILATION ERROR as fTz is marked as final argument

      fTz = Calendar.getInstance().getTimeZone();     
      return ..
    
    }

在复杂的方法中,将参数标记为 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

    public String changeTimezone(final Timestamp stamp, final Timezone fTz, 
            final Timezone toTz){
    
    // THIS WILL CAUSE COMPILATION ERROR as fTz is marked as final argument

      fTz = Calendar.getInstance().getTimeZone();     
      return ..
    
    }

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.

纵性 2024-10-09 05:55:31

我所说的是一般来说将变量和字段标记为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.

×纯※雪 2024-10-09 05:55:31

它只是 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.

眼睛会笑 2024-10-09 05:55:31

- 过去(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.

雪花飘飘的天空 2024-10-09 05:55:31

Final 关键字可防止您为参数分配新值。我想用一个简单的例子来解释这一点

假设我们有一个方法

方法1(){

出生日期 dateOfBirth =new Date("1/1/2009");

方法2(出生日期);

方法3(出生日期); }

public mehod2(出生日期) {
....
....
....
}

public mehod2(出生日期) {
....
....
....
}

情况下,如果在 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

method1(){

Date dateOfBirth =new Date("1/1/2009");

method2(dateOfBirth);

method3(dateOfBirth); }

public mehod2(Date dateOfBirth) {
....
....
....
}

public mehod2(Date dateOfBirth) {
....
....
....
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文