Skip to content Skip to sidebar Skip to footer

Static Initializer Not Called On Activity Creation

I have the following code in my main Activity: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Fabric.with(this, new Crashl

Solution 1:

It's because private static Map<String, MyClass> values = null; is after the static initializer: this assignment will be run after the static initializer block, so it is being assigned a non-null value, and then nulled out.

Move the values field before the initializer block.


BTW, I would decouple the creation of the instances from inserting them into the map, in order to remove the side effects when creating an instance of MyClass. You can also do it without a static initializer block:

publicclassMyClass {
    privatestaticfinal Map<String, MyClass> values = newHashMap<>();

    publicstaticfinalMyClassA= register(newMyClass("a"));
    publicstaticfinalMyClassB= register(newMyClass("b"));
    publicstaticfinalMyClassC= register(newMyClass("c"));

    privatestatic MyClass register(MyClass instance) {
      values.put(instance.name, instance);
      return instance;
    }

    privateMyClass(String name) {
      this.name = name;
    }
    // ...
}

Actually, I wouldn't even do this: I'd use an enum - but I guess there is something in your real code that stops you from doing that.

Post a Comment for "Static Initializer Not Called On Activity Creation"