在 try 块中分配最终变量
非常简短的问题:有没有更优雅的方法来做到这一点:
Object tmp;
try {
tmp = somethingThatCanFail();
} catch (Fail f) {
tmp = null;
}
final Object myObject = tmp;
// now I have a final myObject, which can be used in anonymous classes
Very short question: Is there a more elegant way to do this:
Object tmp;
try {
tmp = somethingThatCanFail();
} catch (Fail f) {
tmp = null;
}
final Object myObject = tmp;
// now I have a final myObject, which can be used in anonymous classes
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以用自己的方法提取价值的创建:
它更长,但根据您对“优雅”的定义,它可能会更优雅。
You could extract the creation of the value in its own method:
It's longer, but depending on your definition of "elegant" it might be more elegant.
取决于你所说的“这个”(和“更优雅”)的意思,
我不确定你为什么认为你需要 tmp 和 myObject,但是如果你想访问它,没有办法避免在 try 块之外使用这些声明之一在 catch 块中。
出了什么问题
Depends what you mean by "this" (and "more elegant")
I'm not sure why you think you need tmp AND myObject, but there's no way to avoid having one of those declarations outside the try block IF you want to access it in the catch block.
What's wrong with
这些天我倾向于这样做
These days I tend to do it like this