Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automatically closing a resource passed as an argument

If I want to automatically close a resource passed as an argument, is there a more elegant solution than this?

void doSomething(OutputStream out) {

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

Ideally, I'd like to have this resource closed automatically, without declaring another variable closeable that refers to the same object as out.

Aside

I realise that closing out within doSomething is considered a bad practice

like image 484
Dónal Avatar asked Aug 14 '18 09:08

Dónal


1 Answers

With Java 9 and higher, you can do

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

This is only allowed if out is final or effectively final. See also the Java Language Specification version 10 14.20.3. try-with-resources.

like image 91
Mark Rotteveel Avatar answered Sep 19 '22 03:09

Mark Rotteveel