在finally块中将对象引用设置为null

发布于 2024-10-11 11:18:10 字数 334 浏览 7 评论 0原文

public void testFinally(){
System.out.println(setOne().toString());

}

protected StringBuilder setOne(){
StringBuilder builder=new StringBuilder();
try{
builder.append("Cool");
return builder.append("Return");
}finally{
builder=null; /* ;) */
}
}

为什么输出是 CoolReturn,而不是 null?

问候,
马亨德拉·阿瑟内里亚

public void testFinally(){
System.out.println(setOne().toString());

}

protected StringBuilder setOne(){
StringBuilder builder=new StringBuilder();
try{
builder.append("Cool");
return builder.append("Return");
}finally{
builder=null; /* ;) */
}
}

why output is CoolReturn, not null?

Regards,
Mahendra Athneria

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

我爱人 2024-10-18 11:18:10

该表达式被计算为 return 语句中的一个值,这就是将返回的值。 finally 块在 return 语句的表达式求值部分之后执行。

当然,finally 块可以修改返回值引用的对象的内容 - 例如:

finally {
  builder.append(" I get the last laugh!");
}

在这种情况下,控制台输出将是“CoolReturn 我笑到了最后!” - 但它不能改变实际返回的值。

The expression is evaluated to a value in the return statement, and that's the value which will be returned. The finally block is executed after the expression evaluation part of the return statement.

Of course, the finally block could modify the contents of the object referred to by the return value - for example:

finally {
  builder.append(" I get the last laugh!");
}

in which case the console output would be "CoolReturn I get the last laugh!" - but it can't change the value which is actually returned.

温柔戏命师 2024-10-18 11:18:10

显然它看起来应该为 null,但是根据 java 中引用传递的概念,它是这样的:

1> return builder.append("Return")... 行被执行,并且 builder 引用的副本返回到 testFinally() 方法通过引用

2>在 finally 块中执行 builder=null 时,builder 引用被取消引用,但堆中的实际对象之前由仍然存在于堆中的构建器引用以及构建器引用的返回副本(这也是指向相同的对象)仍然存在,并且保存着值“CoolReturn”,这就是它打印返回值的原因。

apparently it looks it should be null but with the concept of pass by reference in java here is how it goes :

1> return builder.append("Return")... line gets executed and the copy of builder reference is returned to the testFinally() method by pass by reference

2> While executing builder=null in finally block the builder reference gets dereferenced but the actual object which is in the heap which was referenced by the builder reference earlier still present in the heap and the returned copy of the builder reference (which is also a reference pointing to the same object) still exists and that's holding the value "CoolReturn" , thats why its printing the returned value .

永言不败 2024-10-18 11:18:10

finally 块用于在 try 块执行之后进行“清理”。由于您已经返回了参考,因此您无法以这种方式更改它。

The finally block is used for "cleanup", after the execution of the try block. As you returned the reference already, you can not change it in this way.

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