This section provides a tutorial example on how to load classes into JVM in 3 ways: loadClass() method, Class.forName() method, and 'new' operator.
There are several ways to load a Java class into the JVM:
1. Using the "new" operator: When you use the "new" operator and a class constructor
to create a new instance of a Java class, JVM will use the default ClassLoader to load the class.
This the most common way of loading a Java class. For example:
Object o = new Hello();
Class c = o.getClass();
2. Using the Class.forName() method: When you use the Class.forName() method, JVM will use
the default ClassLoader or the specified ClassLoader to the load the specified class.
For example:
Class c1 = Class.forName("ClassLoaderTest");
Class c2 = Class.forName("Hello", true, currentLoader);
3. Using the ClassLoader.loadClass() method: When you use the Class.forName() method,
JVM will use the given ClassLoader to the load the specified class.
For example:
Class c3 = currentLoader.loadClass("SystemInOut");
Here is tutorial example program showing you how to load a Java class in different ways:
/**
* ClassLoaderLoadClass.java
* Copyright (c) 2010 by Dr. Herong Yang, herongyang.com
*/
class ClassLoaderLoadClass {
public static void main(String[] a) {
java.io.PrintStream out = System.out;
Object o = null;
Class c = null;
ClassLoader l = null;
out.println("");
out.println("Loading with 'new' operator...");
o = new Hello();
c = o.getClass();
out.println("");
out.println("Loading with Class.forName() method...");
try {
c = Class.forName("ClassLoaderTest");
} catch (Exception e) {
e.printStackTrace();
}
out.println("");
out.println("Loading with ClassLoader.loadClass() method...");
l = ClassLoader.getSystemClassLoader();
try {
c = l.loadClass("SystemInOut");
} catch (Exception e) {
e.printStackTrace();
}
out.println("");
out.println("Loading the same class again...");
l = ClassLoader.getSystemClassLoader();
try {
c = l.loadClass("SystemInOut");
} catch (Exception e) {
e.printStackTrace();
}
}
}
When executed on my Windows XP system with JDK 1.6.0,
I got this result:
C:\herong\jvm>javac Hello.java
C:\herong\jvm>javac SystemInOut.java
C:\herong\jvm>javac ClassLoaderTest.java
C:\herong\jvm>javac ClassLoaderLoadClass.java
C:\herong\jvm>java -verbose:class ClassLoaderLoadClass
...
[Loaded java.security.cert.Certificate from shared objects file]
[Loaded ClassLoaderLoadClass from file:/C:/herong/jvm/]
Loading with 'new' operator...
[Loaded Hello from file:/C:/herong/jvm/]
Loading with Class.forName() method...
[Loaded ClassLoaderTest from file:/C:/herong/jvm/]
Loading with ClassLoader.loadClass() method...
[Loaded SystemInOut from file:/C:/herong/jvm/]
Loading the same class again...
[Loaded java.util.AbstractList$Itr from shared objects file]
...
The '-verbose:class' output confirms that all 3 ways of loading classes are working.
If you trying to load the same class again, the JVM will ignore your request.