[英]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.