[英]Close multiple resources with 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
關閉的任何可能場景)?
在資源規范中聲明或引用為資源的變量的類型必須是
AutoCloseable
的子類型,否則會發生編譯時錯誤。
換句話說,只有AutoCloseable
的實例可以與 try-with-resources 一起使用。
關於術語的注釋(也在 JLS 的同一部分中進行了解釋)。 如果你有:
try (AutoCloseable foo = ...;
AutoCloseable bar = ...) {
// do stuff...
} catch (Exception ex) {
// handle exception...
}
那么“資源規范”就是:
(AutoCloseable foo = ...;
AutoCloseable bar = ...)
並且有兩個“資源”: foo
和bar
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.