I'm trying to migrate existing code to try with resource, but not sure how to deal when the closable resources are passed to other methods.
My main concern is how to prevent the developers from touching the method additionalMethod()
from closing the resource by mistake?
Maybe passing around closeable resources is not a good idea at all.
Example of the code:
class SomeClass {
void readMethod() {
try (Scanner scanner = new Scanner(new File("test.txt"))) {
additionalMethod(scanner);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
}
void additionalMethod(Scanner scanner) {
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
// scanner.close() how to ensure no one does this by mistake?
}
}
NOTE: In the example you give, all is happening in the same class. Hence, it is not that much of a problem. Problem happens when you pass it to an alien method. (Method specified in another class)
}
If you have an interface which the closeable objects implements and you can use in an alien method. You can pass using that interface instead of creating an explicit wrapper. For instance;
In this case, you can pass using the reference of type ObjectInterface. (You do not need to create a seperate wrapper because of the fact that the closeable object already implements ObjectInterface and this interface do not expose close operation)
NOTE: In this case, the object could be casted into AutoCloseable.