Static Initialization Blocks

前端 未结 14 1250
暗喜
暗喜 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条回答
  •  清酒与你
    2020-11-22 02:29

    As supplementary, like @Pointy said

    The code in the "static" section(s) will be executed at class load time, before any instances of the class are constructed (and before any static methods are called from elsewhere).

    It's supposed to add System.loadLibrary("I_am_native_library") into static block.

    static{
        System.loadLibrary("I_am_a_library");
    }
    

    It will guarantee no native method be called before the related library is loaded into memory.

    According to loadLibrary from oracle:

    If this method is called more than once with the same library name, the second and subsequent calls are ignored.

    So quite unexpectedly, putting System.loadLibrary is not used to avoid library be loaded multi-times.

提交回复
热议问题