对象引用在finally块中设置为null [英] object reference set to null in finally block

查看:320
本文介绍了对象引用在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?

why output is CoolReturn, not null?

问候,

Mahendra Athneria

Regards,
Mahendra Athneria

推荐答案

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

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.

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

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!");
}

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

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.

这篇关于对象引用在finally块中设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆