Static Initialization Blocks

前端 未结 14 1252
暗喜
暗喜 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:43

    There are a few actual reasons that it is required to exist:

    1. initializing static final members whose initialization might throw an exception
    2. initializing static final members with calculated values

    People tend to use static {} blocks as a convenient way to initialize things that the class depends on within the runtime as well - such as ensuring that particular class is loaded (e.g., JDBC drivers). That can be done in other ways; however, the two things that I mention above can only be done with a construct like the static {} block.

    0 讨论(0)
  • 2020-11-22 02:46

    If your static variables need to be set at runtime then a static {...} block is very helpful.

    For example, if you need to set the static member to a value which is stored in a config file or database.

    Also useful when you want to add values to a static Map member as you can't add these values in the initial member declaration.

    0 讨论(0)
提交回复
热议问题