在finally块中将对象引用设置为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; /* ;) */
}
}
为什么输出是 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该表达式被计算为 return 语句中的一个值,这就是将返回的值。 finally 块在 return 语句的表达式求值部分之后执行。
当然,finally 块可以修改返回值引用的对象的内容 - 例如:
在这种情况下,控制台输出将是“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:
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.
显然它看起来应该为 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 reference2> 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 .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.