Java 9 · Topic 6 of 6
try-with-resources on existing variables
Definition​
Before Java 9 a resource had to be declared inside the try (...) parentheses. Now you can pass a variable that already exists, as long as it is final or effectively final, and Java still closes it for you.
Example code​
Using an existing variable as the resource
class Connection implements AutoCloseable {
Connection() { System.out.println("opened"); }
void query() { System.out.println("query"); }
@Override public void close() { System.out.println("closed"); }
}
class Demo {
public static void main(String[] args) {
Connection connection = new Connection(); // declared earlier
try (connection) { // Java 9: no need to declare it again
connection.query();
}
}
}
// Output:
// opened
// query
// closed
Finished this page? Track your progress (saved only in your browser).