Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Biến effectively final trong try-with-resources Java 9


Mọi biến được sử dụng trong câu lệnh Try with Resource yêu cầu phải được khai báo bên trong câu lệnh Try cho đến phiên bản Java 8. Kể từ Java 9, hạn chế này đã bị bỏ, và bất kỳ biến final hoặc effectively final nào đều có thể dùng bên trong khối Try. Effectively final nghĩa là biến không thể thay đổi sau khi đã được khởi tạo.

Ví dụ

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class EffectivelyFinalTest {
private static File file = new File("try_resources.txt");
public static void main(String args[]) throws IOException {
file.createNewFile();
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
try(bufferedReader) {
System.out.println("Có thể dùng Final hoặc Effectively Final trong Try with Resources!");
} finally {
System.out.println("Trong khối finally");
}
}
}

Kết quả

Có thể dùng Final hoặc Effectively Final trong Try with Resources!
Trong khối finally