簡體   English   中英

class 可以在不實現 AutoCloseable 接口的情況下支持 try-with-resources 嗎?

[英]Can a class support try-with-resources without implementing AutoCloseable interface?

我看到任何實現AutoCloseable接口的 class 都可以使用try-with-resources

public interface AutoCloseable {
  void close() throws Exception;
}

這是 class 支持 Java 中資源嘗試的唯一標准嗎(我的意思是,是否存在 class 不支持嘗試資源AutoCloseable關閉任何可能場景)?

來自Java 語言規范的第 14.20.3 節

在資源規范中聲明或引用為資源的變量的類型必須是AutoCloseable的子類型,否則會發生編譯時錯誤。

換句話說,只有AutoCloseable的實例可以與 try-with-resources 一起使用。


關於術語的注釋(也在 JLS 的同一部分中進行了解釋)。 如果你有:

try (AutoCloseable foo = ...;
     AutoCloseable bar = ...) {
  // do stuff...
} catch (Exception ex) {
  // handle exception...
}

那么“資源規范”就是:

(AutoCloseable foo = ...;
 AutoCloseable bar = ...)

並且有兩個“資源”: foobar

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM