自动关闭作为参数传递的资源



如果我想自动关闭作为参数传递的资源,还有比这更优雅的解决方案吗?

void doSomething(OutputStream out) {
try (OutputStream closeable = out) {
// do something with the OutputStream
}
}

理想情况下,我希望自动关闭此资源,而无需声明另一个引用与out相同的对象的变量closeable

旁白

我意识到在doSomething内关闭out被认为是一种不好的做法

使用 Java 9 及更高版本,您可以

void doSomething(OutputStream out) {
try (out) {
// do something with the OutputStream
}
}

仅当out是最终的或实际上是最终的时,才允许这样做。另请参阅 Java 语言规范版本 10 14.20.3。尝试使用资源。

我使用Java 8,它不支持资源引用。创建接受Closable和有效负载的通用方法怎么样:

public static <T extends Closeable> void doAndClose(T out, Consumer<T> payload) throws Exception {
try {
payload.accept(out);
} finally {
out.close();
}
}

客户端代码可能如下所示:

OutputStream out = null;
doAndClose(out, os -> {
// do something with the OutputStream
});
InputStream in = null;
doAndClose(in, is -> {
// do something with the InputStream
});
void doSomething(OutputStream out) {
try {
// do something with the OutputStream
}
finally {
org.apache.commons.io.IOUtils.closeQuietly(out);
}
}

最新更新