java - 为什么Java7专门引入了AutoCloseable?

标签 java autocloseable

<分区>

AutoCloseable在jdk1.7中引入,Cloesable在jdk1.5中已经存在。

并根据https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

因此,Closeable 实例已经可以在 try-with-resources 语句中被视为资源。这是肯定的,因为 CloseableAutoCloseable 扩展而来。

我的问题是为什么java专门引入了AutoCloseable,为什么不让Closeable只在try-with-resources中支持,有没有其他方法除了 try-with-resources 之外,是否可以使用 AutoCloseable?

最佳答案

Closeable 仅限于抛出 IOException,这可能不适用于某些可关闭但非 IO 绑定(bind)的资源。

AutoCloseable 声明为抛出 Exception,使其更通用。

Closeable 的 API 不能更改为抛出 Exception,因为那将是一个重大更改,因此需要新的 super 接口(interface)。

此外,作为 documented :

Note that unlike the close method of Closeable, this close method is not required to be idempotent. In other words, calling this close method more than once may have some visible side effect, unlike Closeable.close which is required to have no effect if called more than once. However, implementers of this interface are strongly encouraged to make their close methods idempotent.

因此,虽然每个 Closeable 都是 Autocloseable,但反之则不然,将 try-catch-finally 限制为 的语义会受到限制可关闭

关于java - 为什么Java7专门引入了AutoCloseable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26866326/

相关文章:

java - 空对象引用上的 navigationView setText 致命异常

java - 期望EasyMock中的其他参数

JAVA 在每次出现特定符号时在字符串中换行

java - 将对象转换为它们未实现但具有相同方法签名的接口(interface)

java - 尝试在 Java 中使用多个资源

java - 在与主体分开的 try-with-resources 中捕获对象构造期间的错误

java - 工厂创建实例的 AutoCloseable "resource leak"警告?

java - Guava 的 TypeToken 文档中的 "free type variable"是什么?

java - 为什么建议列表在 GWT 中仍然可见

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