我有一个在构建对象时打开的资源。我用它来编写对象的整个生命周期。但是我的应用程序可以在没有警告的情况下关闭,我需要捕获它。课程非常简单。
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();
}
所以,你明白了。如果应用程序出现故障,我想“自动关闭”指标。