如何为构建时打开的资源实现 Autocloseable

How to implement Autocloseable for resource opened on construction

我有一个关于构建我的对象的资源。我用它来编写对象的整个生命周期。但是我的应用程序可以在没有警告的情况下关闭,我需要捕获它。 class 非常简单。

public class SomeWriter {
    private Metrics metrics;

    public SomeWriter() {
        try (metrics = new Metrics()) { // I know I can't but the idea is there
        }
    }

    public void write(String blah) {
       metrics.write(blah);
    }

    public void close() {
       metrics.close();
    }

所以,你明白了。如果应用程序出现故障,我想 "Autoclose" 指标。

try-with-resource 概念无法做到这一点,它仅适用于局部范围。您在 close() 中关闭 Metrics 的方式是您能做的最好的。

最好的办法是让 SomeWriter 也实现 AutoCloseable 并在 try-with-resources 块中使用编写器本身,如

try (SomeWriter writer = new SomeWriter()) {
}
// here, the Metrics will also have been closed.