Java Reference
In-Depth Information
If a system library is loaded more than once by a class loader, an exception occurs. Therefore,
calling loadLibrary for “ mylibrary ” is something you only want to perform once during the
lifetime of this class, and a static initializer is the perfect place for such a task.
What Is a Class Loader?
Every JVM has a built-in class loader object of type java.lang.ClassLoader that is
responsible for the loading of classes into the memory of a Java program. When you
refer to a class in your Java program, the class loader searches the class path for the
appropriate .class fi le and loads the bytecode into memory. For each class that is
loaded, the class loader instantiates a java.lang.Class object.
The class loader loads a class only once, so there is only one Class object for each class
that your program uses. It is here in a Class object that the static fi elds and methods of
your class are stored in memory. The class loader also invokes any static initializers in
a class after the class is loaded. These static initializers allow you to initialize any static
fi elds or perform any onetime tasks for the class.
You can write your own class loader, but the built-in class loader is suffi cient for most
Java applications.
The following MyNumberFormatter class demonstrates a static fi eld getting initialized
in a static initializer. The initialization of the static fi eld involves more than a single
statement, so this is another good example of when to use a static initializer.
1. import java.text.NumberFormat;
2. import java.text.DecimalFormat;
3. import java.util.Locale;
4.
5. public class MyNumberFormatter {
6. public static DecimalFormat df;
7.
8. static {
9. Locale locale = new Locale(“de”); //German
10. NumberFormat nf = NumberFormat.getInstance(locale);
11. df = new DecimalFormat(“#,###.00”);
12. }
13.}
Now that we have seen how static initializers work, we will change topics and discuss
one of the most important elements of a class: methods.
Search WWH ::




Custom Search