This section provides a tutorial example on how to load a given class explicitly using the forName() method and create a new object using the newInstance() method.
Usually, a class can be used loaded implicitly on an on-demand basis
when you create the first object of the class using the "new" operator.
But you can also use Class.forName() methods to load a class expplicitly:
static Class<?> forName(String className) - Returns the Class object associated with the class or interface with the given string name.
static Class<?> forName(String name, boolean initialize, ClassLoader loader) - Returns the Class object associated with the class or interface with the given string name, using the given class loader.
Once a class is loaded as a Class object, a new instance of the class can be
created with the newInstance() method on the Class object.
For example:
Class c = Class.forName("java.util.Date");
java.util.Date d = (java.util.Date) c.newInstance();
The above code is equivalent to:
java.util.Date d = new java.util.Date();
Here is tutorial example program on how to load a class and create a new instance:
/**
* ClassForName.java
* Copyright (c) 2010 by Dr. Herong Yang, herongyang.com
*/
class ClassForName {
public static void main(String[] a) {
java.io.PrintStream out = System.out;
Class c = null;
Object o = null;
// Loading a class explicitly and creating a new instance
try {
c = Class.forName("java.util.Random");
o = c.newInstance();
java.util.Random r = (java.util.Random) o;
out.println("Random number: "+r.nextInt());
} catch (Exception e) {
e.printStackTrace();
}
}
}
When executed on my Windows XP system with JDK 1.6.0,
I got this result:
C:\herong\jvm>java ClassForName
Random number: -1655424893
C:\herong\jvm>java ClassForName
Random number: 1511927719
C:\herong\jvm>java ClassForName
Random number: 1247702944
Note that:
Calling the newInstance() method is equivalent to calling the constructor
of the class with no arguments.
The object returned from the newInstance() method should be casted back to the original class type.