One can load a class dynamically using this method of java.lang.Class
:
public static Class<?> forName(String name, boolean initialize,
ClassLoader loader)
According to the JavaDoc, the second parameter is used to control the timing of class initialization (execution of static initialization code). If true
, the class is initialized after loading and during the execution of this method; if false
, initialization is delayed until the first time the class is used.
Now, I understand all that, but the docs don't say how to decide which strategy to use. Is it better to always do initialization immediately? Is it better to always delay it to first use? Does it depend on the circumstances?
BootStrap ClassLoader: A Bootstrap Classloader is a Machine code which kickstarts the operation when the JVM calls it. It is not a java class. Its job is to load the first pure Java ClassLoader.
Unlike C++, Java supports a special block, called a static block (also called static clause) that can be used for static initialization of a class. This code inside the static block is executed only once: the first time the class is loaded into memory.
Local variables must be initialized before use, as they don't have a default value and the compiler won't let us use an uninitialized value.
Note: It is not necessary to declare fields at the beginning of the class definition, although this is the most common practice. It is only necessary that they be declared and initialized before they are used.
Yes, it depends on circumstances, but usually it is preferred to just let classes be loaded and initialized on first use.
Cases when you might want to early initialize them (e.g. by calling forName()
for them):
HTTPUrlConnection
caches the HTTP user agent returned by System.getProperty("http.agent")
. When it is first used, its value will be cached and if you change it (with like System.setProperty()
), the new value will not be used. You can force such caching if you initialize the proper classes early, protecting them to be modified by the code later on.Cases when you should not initialize early:
AboutDialog
) because this is a rare case and in most runs the user will not do this / need this.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With