Java: When is a static initialization block useful?

前端 未结 13 1607
时光说笑
时光说笑 2020-11-30 16:49

What\'s the difference between initialization within a static block:

public class staticTest {

    sta         


        
相关标签:
13条回答
  • 2020-11-30 17:00

    A static initialization blocks allows more complex initialization, for example using conditionals:

    static double a;
    static {
        if (SomeCondition) {
          a = 0;
        } else {
          a = 1;
        }
    }
    

    Or when more than just construction is required: when using a builder to create your instance, exception handling or work other than creating static fields is necessary.

    A static initialization block also runs after the inline static initializers, so the following is valid:

    static double a;
    static double b = 1;
    
    static {
        a = b * 4; // Evaluates to 4
    }
    
    0 讨论(0)
  • 2020-11-30 17:00

    Exception handling during initialization is another reason. For example:

    static URL url;
    static {
        try {
            url = new URL("https://blahblah.com");
        }
        catch (MalformedURLException mue) {
            //log exception or handle otherwise
        }
    }
    

    This is useful for constructors that annoyingly throw checked exceptions, like above, or else more complex initialization logic that might be exception-prone.

    0 讨论(0)
  • 2020-11-30 17:01

    The static code block enables to initialize the fields with more than instuction, initialize fields in a different order of the declarations and also could be used for conditional intialization.

    More specifically,

    static final String ab = a+b;
    static final String a = "Hello,";
    static final String b = ", world";
    

    will not work because a and b are declared after ab.

    However I could use a static init. block to overcome this.

    static final String ab;
    static final String a;
    static final String b;
    
    static {
      b = ", world";
      a = "Hello";
      ab = a + b;
    }
    
    static final String ab;
    static final String a;
    static final String b;
    
    static {
      b = (...) ? ", world" : ", universe";
      a = "Hello";
      ab = a + b;
    }
    
    0 讨论(0)
  • 2020-11-30 17:04

    Technically, you could get away without it. Some prefer multiline initialisation code to go into a static method. I'm quite happy using a static initialiser for relatively simple multistatement initialisation.

    Of course, I'd almost always make my statics final and point to an unmodifiable object.

    0 讨论(0)
  • 2020-11-30 17:06

    In your example, there is no difference; but often the initial value is more complex than is comfortably expressed in a single expression (e.g., it's a List<String> whose contents are best expressed by a for-loop; or it's a Method that might not exist, so exception-handlers are needed), and/or the static fields need to be set in a specific order.

    0 讨论(0)
  • 2020-11-30 17:06

    static block can be used to initialize singleton instance, to prevent using synchronized getInstance() method.

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