生成的列表/数组由 组成AutoCloseable。是否可以使用try-with-resources关闭列表的所有元素?
因为现在我必须手动编写try-with-resources功能,这不适合我:
Set<AutoCloseable> autoCloseableResources = new HashSet<>();
try {
// генерируем здесь AutoCloseable элементы и добавляем их в множество autoCloseableResources
} catch (Throwable var11) {
var2 = var11;
throw var11;
} finally {
autoCloseableResources
.forEach(resource -> {
if (resource != null) {
if (var2 != null) {
try {
resource.close();
} catch (Throwable var10) {
var2.addSuppressed(var10);
}
} else {
resource.close();
}
}
})
}
autoCloseableResources是否可以使用try-with-resources以某种方式自动关闭列表的所有元素?
写你的
您可以自动使用,只需要在 try-with-resources 中使用一种资源。该资源应该实现
AutoClosable接口,并且可以将样板代码移至实现。