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

时间:2018-08-14 09:17:09

标签: java autocloseable

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

void doSomething(OutputStream out) {

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

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

在旁边

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

3 个答案:

答案 0 :(得分:5)

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

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

仅当out是最终的或实际上是最终的时才允许。另请参见Java Language Specification version 10 14.20.3. try-with-resources

答案 1 :(得分: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
});

答案 2 :(得分:-4)

void doSomething(OutputStream out) {
  try {
    // do something with the OutputStream
  }
  finally {
    org.apache.commons.io.IOUtils.closeQuietly(out);
  }
}