質問

class A{
    static{
      //initialize all things here
    }
}

This is the way I use static blocks in my code. But as we can also keep multiple static blocks in a class

class A{
   static{
      //do something here
   }

   static{
      //do something else here
   }
}

I have seen cases where multiple static blocks have been used, but can't seem to figure out why?

I suppose if it is for readability below method can also be used

class A{
    static{
       someMethod();
       someOtherMethod();
    }
}

Are there any other advantages of multiple static blocks other than readability?

役に立ちましたか?

解決

In your case second one is more readable,as you said. static blocks are executed by the order they placed.In your case there is no other benefits /performance issues.

他のヒント

Not so serious answer: You may use multiple static blocks spread all over the class (at the beginning, the very end) to obfuscate initialization and access to fields and methods. Through this you really well cemented that noone else will touch your class, because slightest changes in those static blocks will completely change the behaviour of your class. ;-)

Somewhat serious: If you have to use these static blocks (of which I am really NOT a fan of, as you might have realized by now), I recommend to put them on the top of the class, well documented and all in one, as you suggested. Depending on the length you might consider static methods. But keep them together, recognizable for the next (poor) soul to work with it.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top