java - 关于jls的一点的澄清

标签 java try-with-resources

直接来自此jls :

A try-with-resources statement with a ResourceSpecification clause that declares multiple resources is treated as if it were multiple try-with-resources statements, each of which has a ResourceSpecification clause that declares a single Resource. When a try-with-resources statement with n Resources (n > 1) is translated, the result is a try-with-resources statement with n-1 Resources. After n such translations, there are n nested try-catch-finally statements, and the overall translation is complete.

对我来说,上述声明的最后部分非常清楚。为什么如果我声明了 n 个资源,那么正如他们所说结果是包含 n-1 个资源的 try-with-resources 语句

为什么不使用 n 资源?

提前致谢。

最佳答案

JLS 试图说明的是,如果您有:

try (
   Closable closeable1 = ...;
   Closable closeable2 = ...;
   // ...
   Closable closeablen = ...;
) {
   // ...
}

它将被反复分解为:

try (Closable closeable1 = ...) {
   try (
      Closable closeable2 = ...;
      // ...
      Closable closeablen = ...;
   ) {
      // ...
   }
}

只要 try 中有多个资源,就会重复此操作。这只是一个说明,因为我假设它被分解为用于 try-with-resources 的实际字节码。

关于java - 关于jls的一点的澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18059448/

相关文章:

java - 如果我自己调用 run() 方法会发生什么?

java - Elasticsearch插件ThreadPermission安全异常

java - 管理不对称资源使用的最佳设计模式

java - 文件处理的资源泄漏,try with resources VS try-catch-finally with file.close()

java - 当键盘处于全屏模式时,EditText 提示不会改变?

Java串行通信: way to set receieve threshold when using async.读取通知

java - 对 CloseableHttpClient 使用 try-with-resource block 是否也会关闭返回的 CloseableHttpResponse?

java - 我应该如何在 JDBC 中使用 try-with-resources?

java - eclipse try-with-resource 模板?

java - 具有自定义主题的 TextView 的不同 textColor