Reputation: 5136
I'm learning java, and in the process of going through the ClassNotFoundException concept, I have come across the term Class.forName("xyz");
. I know that this is one way of loading a class. My question is, what are the different ways of loading a class in java? When to use which one? What is preferred over other?
Upvotes: 7
Views: 11670
Reputation: 49372
I will start with the simplest (Here I assume the class definition is available in the classpath and JVM can load it) :
Reference the class name in the code. The class will be loaded latest when the JVM finds that reference.
SomeClass someInstance = null;
Class.forName(String), to load and initialize the class.It uses classloader of current class.
Class.forName("XYZ");
ClassLoader#loadClass(String), to load class, but doesn't initialize.You can get an instance of ClassLoader
and invoke loadClass()
on that instance, which can be a Custom ClassLoader or System ClassLoader.
ClassLoader.getSystemClassLoader().loadClass("XYZ");
Overloaded Class.forName() , allows you to specify the classloader to use explicitly and initialize
parameter to specify whether the class must be initialzed.
Class.forName(String name, boolean initialize, ClassLoader loader)
For JDBC
, we need to load the driver class as well as initialize it. Somewhere the driver class gets registered with the JDBC Driver Manager by running some static initializer(though I haven't seen the inner working code). Hence we need to use a class loading mechanism where the driver class gets loaded and its static initialization blocks run. Hence the most preferred way is Class.forName()
.
Upvotes: 17