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

Static Block ใน Java: ตัวอย่างและการทำงาน

Static Block (Static Initializer)

บล็อกโค้ดที่รันครั้งเดียวเมื่อ class ถูกโหลดโดย ClassLoader ก่อน main method ใช้สำหรับ initialization ที่ซับซ้อนของ static fields

ตัวอย่างพื้นฐาน


class Demo {
    static int staticVal;
    int instanceVal;
    
    static {
        staticVal = 67;
        System.out.println("Static block executed");
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("Value: " + Demo.staticVal);
    }
}

ผลลัพธ์

Static block executed
Value: 67

หลาย Static Blocks

รันตามลำดับที่เขียนใน source code


public class Demo {
    static { System.out.println("Block 1"); }
    static { System.out.println("Block 2"); }
    static { System.out.println("Block 3"); }
    
    public static void main(String[] args) {
        System.out.println("Main");
    }
}

ผลลัพธ์

Block 1
Block 2
Block 3
Main

Use Cases

  • Initialize static collections/maps ที่ซับซ้อน
  • Load native libraries: static { System.loadLibrary("mylib"); }
  • Register JDBC drivers (เก่า)
  • Setup logging configuration
  • Compute ค่าคงที่ที่ต้องใช้ logic/loop

ข้อจำกัด

  • ไม่สามารถใช้ this, super ได้
  • ไม่สามารถเรียก instance methods/fields ได้โดยตรง
  • ไม่สามารถ throw checked exceptions ได้ (ต้อง catch ภายใน หรือ declare ใน constructor ทุกตัว)
  • รันครั้งเดียวต่อ ClassLoader (อาจรันซ้ำถ้า class โหลดโดย ClassLoader ต่างกัน)