Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Static Initialization Block  RSS feed

 
S Chet
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone answer this? In what way is a Static initialization block used?
 
Sol Mayer-Orn
Ranch Hand
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Here are 2 cases when I often use static initializers.
Other programmers could probably add more scenarios.

1. When I'd like to initialize some static members, but the initial value is too complex to be calculated at a simple declaration lines.
For example:


2. When you'd like some resources to be initialized and made available before anyone uses the class. Some well-known examples:
a) JNI : when a java class has native methods, for example methods that invoke compiled C++ libraries stored in a DLL. Then your class would usually have a static initializer that loads the required DLL, so that its available for use by your java class.
b) JDBC drivers: most JDBC tutorials would tell you to start by 'loading' the jdbc driver using 'Class.forName'.
When you call 'Class.forName', you acaully invoke the driver's static initializer, which usually registers this driver with the 'DriverManager' (if i'm not mistaken) - so that, from now on, DriverManager knows about the driver and can use it for opening connections.

Hope this helps.
 
S Chet
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I get the idea. Thank you Sol.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!