Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Effectively Final Variables ใน try-with-resources Java 9

ก่อน Java 9 ตัวแปรใน try-with-resources ต้องประกาศภายใน try เท่านั้น ตั้งแต่ Java 9 ใช้ final หรือ effectively final variables ได้ (effectively final = ไม่เปลี่ยนค่าหลัง initialize)

ตัวอย่าง

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

public class EffectivelyFinalExample {
    private static File file = new File("try_resources.txt");
    
    public static void main(String args[]) throws IOException {
        file.createNewFile();
        BufferedReader reader = new BufferedReader(new FileReader(file));
        
        // ใช้ effectively final variable 'reader' ใน try
        try (reader) {
            System.out.println("Can use final/effectively final in try-with-resources!");
        } finally {
            System.out.println("In finally block");
        }
    }
}

ผลลัพธ์

Can use final/effectively final in try-with-resources!
In finally block