jdk 1.7中try块中Autocloseable的新概念是什么

What is the new concept of Autocloseable in try block in jdk 1.7

jdk1.7.try 块中Autocloseable 的新概念是什么。这真的是必需的还是只是为了增强 try catch 块中的某些内容以使其更先进。

它允许使用 try-with-resources,这是 Java 7 的新功能。

守旧派:

InputStream is = null;
try {
    is = ...;
    // do stuff with is...
} catch (IOException e) {
    // handle exception
} finally {
    if (is != null) {
        try {
            is.close();
        } catch (IOException innerE) {
            // Handle exception
        }
    }
}

新学校:

try (InputStream is = ...) {
    // do stuff with is...
} catch (IOException e) {
    // handle exception
}

AutoCloseable 对象可以在 try 块(在 () 内)中打开,并且将 自动关闭 而不是使用finally 块,如上面的代码示例。

来自Oracle docs

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. 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.

所以,这意味着所有 AutoCloseable 的对象都可以这样使用,这意味着例如ResultSet等资源可以通过try-with-resources方式使用。 IMO,这简化了编码和可读性

但是,可读性并不是为什么 使用new 方式的杀手锏。我相信资源是自动关闭是一个简单的事实。在 Java 7 之前使用时,可能会忘记进行空值检查或关闭底层资源 - try-with-resources 更不容易出错。

但是,话虽如此。 不需要使用 try-with-resources,尽管我不推荐,但仍然可以使用 老派 方式它到期了(因为它既冗长又容易出错)。

阅读 Java 7 中引入的 try-with-resources 功能的文档。

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. 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.

以及 JavaAutoCloseable#close() 的文档:

Closes this resource, relinquishing any underlying resources. This method is invoked automatically on objects managed by the try-with-resources statement.

这意味着您可以创建自己的 AutoCloseable 资源子类型并在此语句中使用它们。

try (BufferedReader br = new BufferedReader(new InputStreamReader)) {
    // try block
} catch (IOException e) {
    // No need to close resourse. Only handle exception. Resource will be closed automatically
}

java 中有许多 类 实现了 Autoclosable。

下面 link 列出了实现此接口的 类。

http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html