最终方法参数与将参数重新声明为方法中的最终变量
Final method arguments vs re-declaration of arguments as final variables in the method
我找到了类似下面的方法:
private void methodA(String firstArg, String secondArg) {
final String queueFirstArg = firstArg;
final String queueSecondArg = secondArg;
executor.execute(new Runnable() {
public void run() {
methodB(queueFirstArg, queueSecondArg);
}
}
}
代码看起来很糟糕,使两个参数 'final' 就足够了。
我错过了什么吗?使用这种方法有什么好处吗?
是的,它是 "bad code",因为有多余的局部变量,因为您可以将 final 添加到参数中,而不用害怕改变调用者的行为,请参阅 answer:
Java always makes a copy of parameters before sending them to methods. This means the final doesn't mean any difference for the calling code.
我找到了类似下面的方法:
private void methodA(String firstArg, String secondArg) {
final String queueFirstArg = firstArg;
final String queueSecondArg = secondArg;
executor.execute(new Runnable() {
public void run() {
methodB(queueFirstArg, queueSecondArg);
}
}
}
代码看起来很糟糕,使两个参数 'final' 就足够了。 我错过了什么吗?使用这种方法有什么好处吗?
是的,它是 "bad code",因为有多余的局部变量,因为您可以将 final 添加到参数中,而不用害怕改变调用者的行为,请参阅 answer:
Java always makes a copy of parameters before sending them to methods. This means the final doesn't mean any difference for the calling code.