如何使这个变量引用“final”,如何让它干净地编译?
我想将 result
变量设为 final
,如何构建此代码以便干净地编译?我知道我过去曾这样做过,但我不记得我是如何构建它以使其发挥作用的。
下面的代码是一个稻草人示例,我试图清理的代码要复杂得多,这只是提炼出我想要完成的事情的本质。
private boolean someMethod()
{
final boolean result;
try
{
// do the logic here that might throw the following
// exceptions
}
catch (final IOException ioe)
{
result = false;
}
catch (final ClassNotFoundException cnfe)
{
result = false;
}
return result;
}
我无法将 result = true
放入 try
块中,因为它不会使用两个 catch 块进行编译,并抱怨最终变量可能已被分配。
我无法将其放入 finally
块中,因为这会产生与 try
块中相同的抱怨?
我希望能够设置 result =
一次且仅一次。
那么你在哪里设置 result = true;
来获取它干净地编译?
I want to make the result
variable final
, how do I structure this code so that this compiles cleanly? I know I have done this in the past, but I can't remember how I structured it to make it work.
The following code is a straw man
example, the code I am trying to clean up is much more complicated, this is just distilling the essence of what I am trying to accomplish.
private boolean someMethod()
{
final boolean result;
try
{
// do the logic here that might throw the following
// exceptions
}
catch (final IOException ioe)
{
result = false;
}
catch (final ClassNotFoundException cnfe)
{
result = false;
}
return result;
}
I can't put the result = true
in the try
block because it won't compile with both the catch blocks complaining that the final variable might already be assigned.
I can't put it in a finally
block because that would generate the same complaints as in the try
block?
I want to be able to set result =
once and only once.
So where do you set result = true;
to get it to compile cleanly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不设置变量要简单得多。
It's a lot simpler to not set a variable.
尝试使用
final
来强制“只分配一次”总是很棘手的。您可以使用第二个变量:但真正的问题是,为什么不直接删除
final
限定符呢?Trying to use
final
to enforce "assign exactly once" is always tricky. You can use a second variable:But the real question is, why not just remove the
final
qualifier?您无法将值重新分配给
final
变量,因此这是不可能的。编辑:想要将方法本地的变量声明为
final
并在同一方法中更改值也是矛盾的 - 为什么有必要将其声明为final< /code> 到底在这个方法中吗?
You cannot reassign a value to a
final
variable, so this is impossible.edit: It's also a contradiction to want to declare a variable that is local to a method as
final
and also change the value in the same method - why is it necessary to declare it asfinal
at all in this method?如果您在方法中将局部变量声明为
final
,则该变量的值无法在该方法中更改。从
result
的声明中删除final
,或者完全删除result
局部变量并直接从catch< 中返回/code> 块和方法结束。
If you declare a local variable as
final
within a method then the value of that variable cannot be changed within the method.Remove the
final
from the declaration ofresult
, or get rid of theresult
local variable altogether and return directly from within thecatch
blocks and the end of the method.