我有一个在构建对象时打开的资源。我用它在对象的整个生命周期中进行写入。但我的应用程序可能会在没有警告的情况下关闭,我需要捕获这一点。该类非常简单。
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();
}
所以,你明白了。如果应用程序出现故障,我希望“自动关闭”指标。
最佳答案
这对于 try-with-resource 概念来说是不可能的,它仅适用于本地范围。您可以在 close()
中关闭 Metrics
的最佳方式。
最好的办法是让 SomeWriter
也实现 AutoCloseable
并在 try-with-resources block 中使用 writer 本身,如下所示
try (SomeWriter writer = new SomeWriter()) {
}
// here, the Metrics will also have been closed.
关于java - 如何对构建时打开的资源实现 Autocloseable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49493942/