在 java 中添加 AutoCloseable 很重要吗?

Is it important to add AutoCloseable in java?

在 java 中实施 AutoCloseable 重要吗?

如果我创建一个实现 AutoCloseable 的 class 扩展另一个未实现它的 class 是否有意义?

例如

public class IGetClosed extends ICannotBeClosed implements AutoCloseable {...}

AutoCloseable 是一个接口,它本质上允许 object 的资源在 try-with-resources 语句中使用时自动关闭。如果您不打算将 object 与 try-with-resources 一起使用,则根本没有必要实施它。

作为继承的规则,不,做您想做的事本质上没有错。如果您想 child class 中的 auto-close 资源,请继续。

有一个 class 实现 AutoClosable 没有问题,即使它是超级 class 也没有。实际上,由于 Java 中的所有 class 直接或间接地扩展了 java.lang.Object,所以所有 AutoClosable 最终都扩展了一个 class 而没有实现这个界面。

如果您的 class 具有某些 closeing 的语义,您可能应该让它实现 AutoClosable。这样做几乎不需要任何成本,如果有的话,它允许您使用 Java 7 对 try-with-resource 语法的简洁语法糖化。

来自文档:

void close() throws Exception

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

While this interface method is declared to throw Exception, implementers are strongly encouraged to declare concrete implementations of the close method to throw more specific exceptions, or to throw no exception at all if the close operation cannot fail.

因此,如果您希望新的 class 在 try-with-resources 语句中自动关闭,您可以将该功能添加到 ICannotBeClosed class。

Is it important to implement autoCloseable in java?

很难说实现接口重要与否。但这不是必需的。

Would it make sense if I create a class which implement AutoCloseable extends a other class which doesn't implement it?

这样做是可以的。没问题。

AutoCloseable 是从 Java 7 添加的。它旨在与新的 try-with-resources 语句一起使用 (Java 7+)

请参阅下面的两个 类 提供相同的功能。一个不使用 AutoCloseable,另一个使用 AutoClosable:

// Not use AutoClosable
public class CloseableImpl {
    public void doSomething() throws Exception { // ... }
    public void close() throws Exception { // ...}
    
    public static void main(String[] args) {
        CloseableImpl impl = new CloseableImpl();
        try {
            impl.doSomething();

        } catch (Exception e) {
            // ex from doSomething
        } finally {
            try { //  impl.close() must be called explicitly
                impl.close();
            } catch (Exception e) { }
        }
    }
}

// Use AutoCloseable 
public class AutoCloseableImpl implements AutoCloseable {
    public void doSomething() throws Exception { // ... }
    public void close() throws Exception { // ...}

    public static void main(String[] args) {
        // impl.close() will be called implicitly

        try (AutoCloseableImpl impl = new AutoCloseableImpl()) {
            impl.doSomething();
        } catch (Exception e) {
          // ex from doSomething or close
        }
    }
}

如你所见。使用 AutoClosble 将使代码更短更清晰。