最终关键字实际上是如何工作的,我感到困惑...
在try块运行完成之前,它将返回到调用该方法的位置。但是,在返回调用方法之前,finally块中的代码仍然会执行。因此,请记住,即使try块中某处有return语句,finally块中的代码仍将执行。
当我运行代码时,我得到5而不是我期望的10
public class Main {
static int count = 0;
Long x;
static Dog d = new Dog(5);
public static void main(String[] args) throws Exception {
System.out.println(xDog(d).getId());
}
public static Dog xDog(Dog d) {
try {
return d;
} catch (Exception e) {
} finally {
d = new Dog(10);
}
return d;
}
}
public class Dog {
private int id;
public Dog(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
finally块不是在return语句之前执行,而是在实际返回之前执行。这意味着inreturn
语句中的表达式是在执行finally块之前求值的。在您的情况下,在编写表达式时,return d
将对d
表达式求值并存储到寄存器中,然后finally
执行该表达式并返回该寄存器中的值。无法更改该寄存器的内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句