为什么Java的try-with-resource需要声明 [英] Why is declaration required in Java's try-with-resource

查看:106
本文介绍了为什么Java的try-with-resource需要声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java7的try-with-resources非常棒,但我无法理解为什么需要在尝试中包含资源声明声明。我的直觉说以下应该是可能的:

Java7's try-with-resources is great and all, but I can't wrap my head around why it is required to include the declaration of the resource in the try statement. My gut says the following should be possible:

CloseableResource thing;
try (thing = methodThatCreatesAThingAndDoesSomeSideEffect()) {
    // do some interesting things
}
thing.collectSomeStats();

唉,这会导致语法错误(隐藏地期望; )。将类型定义/声明移动到 try 语句中,这当然会将事物移动到相应的范围中。当我想从 AutoClosable 获得更多信息时,我可以弄清楚如何解决这个问题,而不是关闭,我对为什么编译器需要它感兴趣像这样。

Alas, this results in a syntax error (cryptically expecting a ;). Moving the type definition/declaration into the try statement works, which of course moves thing into the corresponding scope. I can figure out how to work around this when I want more from my AutoClosable than getting closed, I'm interested in why the compiler requires it like this.

推荐答案

您的版本没有明确定义应该关闭的内容,例如

Your version does not clearly define what should be closed, for example

CloseableResource thing;
Parameter a;

try (a = (thing = methodThatCreatesAThingAndDoesSomeSideEffect()).getParameter()) {

如果你写的话该怎么办

try (12) {

或其他什么?

CloseableResource thing1 = methodThatCreatesAThingAndDoesSomeSideEffect();
CloseableResource thing2 = methodThatCreatesAThingAndDoesSomeSideEffect();

try(thing1) {
}

为什么只关闭 thing1

因此当前语法强制您同时打开关闭块来创建变量。

So the current syntax force you to create a variable simultaneosly with opening close block.

ALSO2

CloseableResource thing1 = methodThatCreatesAThingAndDoesSomeSideEffect();

CloseableResource thing1 = methodThatCreatesAThingAndDoesSomeSideEffect();

try(thing1) {
}

thing1.doSomethingOnClosedResource();

因为 thing1 仍然存在。

这篇关于为什么Java的try-with-resource需要声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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