Try-with-resources Improvement
Try-with-resources มาตั้งแต่ Java 7 ปิด resource อัตโนมัติ แต่จำเป็นต้องประกาศ resource ใน try statement
Java 9 ปรับปรุง: ไม่ต้องประกาศ object ใหม่ใน try statement ได้ ใช้ variable ที่ประกาศไว้ภายนอกได้
ตัวอย่าง
import java.io.*;
public class TryWithResourceTest {
public static void main(String[] args) throws FileNotFoundException {
String line;
Reader reader = new StringReader("tutorialspoint");
BufferedReader breader = new BufferedReader(reader);
// ใช้ variable ที่ประกาศไว้ข้างนอกโดยตรง
try (breader) {
while ((line = breader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Output
tutorialspoint
ข้อดี
- โค้ดสะอาดขึ้น แยก declaration และ usage
- ใช้ resource object ที่สร้างไว้ก่อนหน้าได้ (effectively final)
- ลด nested blocks
ข้อจำกัด
Variable ต้องเป็น effectively final (ไม่ถูก reassign หลังสร้าง)
สรุป
Java 9 ทำให้ try-with-resources ยืดหยุ่นขึ้น เขียนโค้ดสะอาดและอ่านง่ายกว่าเดิม