Wednesday 15 January 2014

java - Static block is never run -


I have a utility class that looks like this:

  Public Ultimate Class MyUtils {The public stable final list & lt; String & gt; MY_VALUES = New Arrestist & lt; String & gt; (); {MY_VALUES.add ("foo"); MY_VALUES.add ("bar"); }}   

I call it from another class like this:

  MyUtils.MY_VALUES   

If I do so, the list is empty and if I debug it, then I think the static block never runs.

As I understand the answers and the block should be run when is assigned a stable area of ​​class , which I am currently doing. I also tried to make the variable non-last to complete the condition "a non-static static field is used ".

I can use an init method, in other questions and ALS, but I still want to understand why it is not working at the first place, although I think the language specification The conditions are fulfilled from

You must add static keyword to your block to make it static :

  public final range MyUtils {public static final list & lt; String & gt; MY_VALUES = New Arrestist & lt; String & gt; (); Stable {MY_VALUES.add ("foo"); MY_VALUES.add ("bar"); }}   

A initialization block is created square each time.

A Static initialization block becomes called only once at the beginning of your program.

No comments:

Post a Comment