java - 为什么 try-with-resource 需要一个局部变量?

标签 java try-with-resources

引用我的问题 Any risk in a AutoCloseable wrapper for java.util.concurrent.locks.Lock? ,我想知道为什么 try-with-resource-statement 需要一个 named 局部变量。

我目前的使用情况如下:

try (AutoCloseableReentrantReadWiteLock.Lock l = _lock.writeLock()) {
    // do something
}        

变量 l 在 try block 内未使用,只会污染命名空间。据我所知,类似的 C# using 语句不需要局部命名变量。

由于在 try block 结束时关闭了匿名局部变量,是否有任何原因无法支持以下内容?

try (_lock.writeLock()) {
    // do something
}        

最佳答案

@McDowell 评论中的链接揭示了 a blog post comment 中的正确答案由领导 the Java Technology Specification 的乔·达西 (Joe Darcy) 撰写引入了 try-with-resources 语句:

Back in JDK 7, we started with a try-with-resources construct like that allowed a general expression to be used for the resource, including a method call. However, the expert group found by the early draft review (http://jcp.org/aboutJava/communityprocess/edr/jsr334/index.html) that

"A possible future change [to the try-with-resources statemenbt] is dropping support for a resource to be specified as a general Expression. Nontrivial specification and implementation complexities arise from allowing a general Expression to be used as resource. A restricted expression that could be an identifier or a PrimaryNoNewArray may suffice. Even the more severe restriction of just allowing an identifier may provide nearly all the additional utility of allowing a full expression (over forcing the declaration of a new resource variable) at a much lower marginal implementation and specification impact."

By the end of JDK 7, what we wanted was a fresh variable declaration for the resource or an existing final / effectively final variable. We only had time to provide the former in 7; in 9, we are providing the latter too.

关于java - 为什么 try-with-resource 需要一个局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16588843/

相关文章:

java - 使用 Java 8 将字符串转换为对象列表

java - Java 程序终止时未能关闭文件有什么危害吗?

java - 将方法参数的所有权传递给 'try with resources' block

java - 调用 super 构造函数时尝试资源

java - 为什么 Java 提示我的 try-with-resources block ?

Java 风格 : Variable declaration in a switch

java - 在 Java 的排序列表中搜索字符串,并可能搜索以部分字符串开头的所有字符串

java - 列标题中带有 “close” 按钮的 JTable

java - auth-constrain 和 security-role 之间有什么区别?

Java - try-with-resources 中的 ZipOutputStream