Static Initialization Blocks

前端 未结 14 1575
暗喜
暗喜 2020-11-22 01:56

As far as I understood the \"static initialization block\" is used to set values of static field if it cannot be done in one line.

But I do not understand why we ne

14条回答
  •  猫巷女王i
    2020-11-22 02:42

    It's also useful when you actually don't want to assign the value to anything, such as loading some class only once during runtime.

    E.g.

    static {
        try {
            Class.forName("com.example.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new ExceptionInInitializerError("Cannot load JDBC driver.", e);
        }
    }
    

    Hey, there's another benefit, you can use it to handle exceptions. Imagine that getStuff() here throws an Exception which really belongs in a catch block:

    private static Object stuff = getStuff(); // Won't compile: unhandled exception.
    

    then a static initializer is useful here. You can handle the exception there.

    Another example is to do stuff afterwards which can't be done during assigning:

    private static Properties config = new Properties();
    
    static {
        try { 
            config.load(Thread.currentThread().getClassLoader().getResourceAsStream("config.properties");
        } catch (IOException e) {
            throw new ExceptionInInitializerError("Cannot load properties file.", e);
        }
    }
    

    To come back to the JDBC driver example, any decent JDBC driver itself also makes use of the static initializer to register itself in the DriverManager. Also see this and this answer.

提交回复
热议问题