I want to add that static variables and static initializers are executed in the order of appearance during class loading. So, if your static initializer relies on some kind of static variable, it should be initialized before a specific static block, for example.
final static String JDBC_DRIVER = getJdbcDriver( ); static { try { Class.forName(JDBC_DRIVER); } catch ( ClassNotFoundException exception ) { log.error( "ClassNotFoundException " + exception.getMessage( ) ); } }
In this example, getJdbcDriver will execute before the static initializer. In addition, the class may have a more static initializer. Once again they are executed in order of appearance.
I also want to mention the existence of instance initializers here, since they really surprise when they were first seen. They look like a block of code inside the class body, for example.
class MyClass { final int intVar; { intVar = 1; } }
In general, their use is somewhat unnecessary due to the constructor, but they are useful in implementing Java versions of closures.
Alexander Pogrebnyak
source share