![](/img/trans.png)
[英]Hibernate “The resource type Session does not implement java.lang.AutoCloseable”
[英]How to implement Autocloseable for resource opened on construction
我有打开我的对象构造的资源。 我用它来写对象的整个生命周期。 但是我的应用程序可以关闭而不会发出警告,我需要捕获这一点。 该类非常简单。
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();
}
这样,您就知道了。 如果应用程序出现故障,我想“自动关闭”指标。
使用资源试一试的概念是不可能的,仅适用于本地范围。 在close()
关闭Metrics
的方法是最好的方法。
最好的选择是让SomeWriter
也实现AutoCloseable
并在try-with-resources块中使用writer本身,例如
try (SomeWriter writer = new SomeWriter()) {
}
// here, the Metrics will also have been closed.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.