Try-with-resources improvement
Use existing effectively-final variables directly in try-with-resources.
Porównanie kodu
✕ Java 8
Connection conn = getConnection();
// Must re-declare in try
try (Connection c = conn) {
use(c);
}
✓ Java 9+
Connection conn = getConnection();
// Use existing variable directly
try (conn) {
use(conn);
}
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
No re-declaration
Use the existing variable name directly.
Less confusion
No separate variable name inside the try block.
Concise
Fewer lines, same resource safety.
Stare podejście
Re-declare Variable
Nowoczesne podejście
Effectively Final
Od JDK
9
Poziom trudności
Początkujący
Wsparcie JDK
Try-with-resources improvement
Dostępne
Widely available since JDK 9 (Sept 2017)
Jak to działa
Java 9 allows effectively-final variables to be used directly in try-with-resources without re-declaration. This is cleaner when the resource was created outside the try block.
Powiązana dokumentacja