1

From my Java understanding, static blocks should be executed before ANY other function.

I have a static block that calls a static function, both in class MyClass.java, that uses SharedPreferences object.

MyClass is used by MyApplication (Extends Application), somewhere in the onCreateMethod.

static {
    doSomethingStaticFirst();
}

private static void doSomethingStaticFirst() {

        //Log(DO_SOMETHING_STATIC_FIRST)

        UserPreferences userPreferences = new UserPreferences(MyApplication.getInstance().getApplicationContext());
}

However I am seeing the following logs in order:

  1. MyApplication onCreate method
  2. DatabaseManager onUpdate (in case DB version increased)
  3. DO_SOMETHING_STATIC_FIRST

Is there a particular reason why static blocks are not executed first? Will MyApplication onCreate method will be executed first over all?

htafoya
  • 18,261
  • 11
  • 80
  • 104
  • In what class is the code you have shown? Is it in `MyApplication`? Is it in `DatabaseManager`? Is it somewhere else? – CommonsWare Nov 19 '15 at 00:46
  • Somewhere else, in a class that is used by MyApplication – htafoya Nov 19 '15 at 00:58
  • Possible duplicate of [When is the static block of a class executed?](http://stackoverflow.com/questions/9130461/when-is-the-static-block-of-a-class-executed) – Krease Nov 19 '15 at 01:00

1 Answers1

7

Your assumption is not accurate.

Static blocks in a class are executed when your class is loaded - which occurs the first time it is referenced in code.

If you really need to have your static block execute earlier, you can force-load the class - something like Class.forName("com.foo.MyClassWithStaticFunctions") earlier in the execution path will force the static blocks to execute sooner.

Krease
  • 15,805
  • 8
  • 54
  • 86