0

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

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();
    }

所以,你明白了。如果应用程序出现故障,我想“自动关闭”指标。

4

1 回答 1

2

仅适用于本地范围的 try-with-resource 概念无法做到这一点。你关闭Metrics内在的方式close()是你能做的最好的。

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

try (SomeWriter writer = new SomeWriter()) {
}
// here, the Metrics will also have been closed.
于 2018-03-26T14:39:23.717 回答