我在想,在传递 java.lang.Number 实例(例如 java.lang.Long)时,在方法签名中使用 Final 关键字是否有意义?
我认为这没有任何意义,因为java通过值传递对象尊重。这意味着 java 将原始引用的副本传递给该方法。此 Number 值的任何更改在该方法之外都是不可见的。所以方法改变或者方法内部的值不变并不重要。
当然,当我们将 pojo 传递给方法时,使用 Final 关键字是有意义的,但这是一个不同的场景。
java.lang.Number 演示
public class Demo {
public static void main(String[] args) {
Long longValue = 1L;
System.out.println("Long before: " + longValue);
System.out.println(trickyMethod(longValue));
System.out.println("Long after: " + longValue);
BigInteger bigIntegerValue = BigInteger.ONE;
System.out.println("BigInteger before: "+ bigIntegerValue);
System.out.println(trickyMethod(bigIntegerValue));
System.out.println("BigInteger after: " + bigIntegerValue);
}
private static String trickyMethod(Long value) {
value = 10L;
System.out.println(" trickyMethod: " + value);
if (value.equals(10L))
return " equal";
else
return " different";
}
private static String trickyMethod(BigInteger value) {
value = BigInteger.TEN;
System.out.println(" trickyMethod: " + value);
if (value.equals(BigInteger.TEN))
return " equal";
else
return " different";
}
}
和输出
Long before: 1
trickyMethod: 10
equal
Long after: 1
BigInteger before: 1
trickyMethod: 10
equal
BigInteger after: 1
POJO 演示
public class Demo {
static class Container {
private Long l;
public Container(Long l) {
this.l = l;
}
@Override
public String toString() {
return String.valueOf(l);
}
@Override
public boolean equals(Object obj) {
Container c = (Container) obj;
return l.equals(c.l);
}
}
public static void main(String[] args) {
Container container = new Container(1L);
System.out.println("Container before: "+ container);
System.out.println(trickyMethod(container));
System.out.println("Container after: " + container);
}
private static String trickyMethod(final Container container) {
container.l = 10L;
System.out.println(" trickyMethod: " + container);
if (container.equals(new Container(10L)))
return " equal";
else
return " different";
}
}
和输出
Container before: 1
trickyMethod: 10
equal
Container after: 10
为什么开发人员在 Long
的情况下在方法签名中使用像 String method(final Long value)
这样的 Final 关键字?
最佳答案
参数是否不可变并不重要。最终可变参数可以在内部修改,只是不能将任何内容重新分配给参数变量。
Java 中最无用的东西之一,如果参数是隐式最终的,那就太好了,因为如果您重新分配参数,就会产生代码味道。大多数代码分析器将其报告为错误/警告等。
基本的经验法则是,除非语法上需要将参数设置为final
(在极少数情况下),否则不要费心将final放入参数中,因为它只会在参数中造成无用的困惑。代码。但是,切勿重新分配参数,因为它可能容易出现错误,并且假装所有参数都是最终参数。
关于java - 将 java.lang.Number 实例传递给方法时的 Final 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42315863/