0

I have a utility class that looks like this:

public final class MyUtils {

     public static final List<String> MY_VALUES = new ArrayList<String>();

     {
         MY_VALUES.add("foo");
         MY_VALUES.add("bar");
     }
}

I call this from another class just like this:

MyUtils.MY_VALUES

If I do so, the list is empty and if I debug I see the static block is never run.

As I understand from the answers to When does static class initialization happen? and How to force a class to be initialised? the block should run when a static field of the class is assigned, which I do right away. I also tried making the variable non-final to fulfill the condition "a non-constant static field is used".

I could use an init method as also sugested in the two other questions and als in Why doesn't my static block of code execute? but I would still like to understand why it isn't working in the first place although I seem to have fulfilled the conditions from the language specification.

Community
  • 1
  • 1
André Stannek
  • 7,773
  • 31
  • 52

1 Answers1

8

You have to add the static keyword in front of your block in order to make it static:

public final class MyUtils {

     public static final List<String> MY_VALUES = new ArrayList<String>();

     static {
         MY_VALUES.add("foo");
         MY_VALUES.add("bar");
     }
}

A initialization block gets called everytime the class is constructed.

A static initialization block gets called only once at the start of your program.

Stefan Fandler
  • 1,141
  • 7
  • 13
  • That works, thanks. Will be a few minutes until I can accept your answer. Could you explain what the difference to the construct without the `static` keyword is? I used that before and it always worked so far (e.g. if I call static methods, the block was run before). – André Stannek Mar 27 '13 at 01:13
  • 1
    Not exactly correct. Initialization block gets called every time **object** of the class is constructed. A static initialization block gets called first time the class is used (more or less). – zch Mar 27 '13 at 17:48