Class.forName("X") helps us to
load class dynamically(at runtime) using its fully qualified name
(package.classname) and JVM executes all its static block after class loading.
Note: It does not return the instance of Class.
forName() uses the classloader to invoke the
class.
If a class already loaded in JVM, Class.forName()
does not load that class i.e. JVM keeps track of all the
classes that have been previously loaded.
public class ClassForName {
public ClassForName() {
System.out.println("ClassForName Constructor");
}
public static String methodName = "ClassForName";
static {
System.out.println("static block in ClassForName");
}
}
public class TestForname {
}
public class TestForname {
public static void main(String[] args) {
try {
Class c = Class.forName("core.forname.ClassForName");
ClassForName name = (ClassForName)c.newInstance();
System.out.println("The second time calls forName:");
Class c1 = Class.forName("core.forname.ClassForName");
} catch (InstantiationException
| IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e)
{
System.out.println("ClassNotFoundException");
}
}
}
Output:
The output is
static block
in ClassForName
ClassForName
Constructor
The second
time calls forName:
JDBC Driver Is a Good Example
We generally uses it load the JDBC
Drivers.
If class successfully loaded, the
static initializer is called.
Class.forName("org.gjt.mm.mysql.Driver");
Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");
Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");
No comments:
Post a Comment