forName() Method - Loading Classes

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:

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, HerongYang.com, All Rights Reserved.
 */
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 7 system with JDK 1.7.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:

When tested with program with JDK 1.6.0 in 2010, I got the same results.

Last update: 2014.

Table of Contents

 About This Book

 Downloading and Installing JDK 1.8.0 on Windows

 Downloading and Installing JDK 1.7.0 on Windows

 java.lang.Runtime Class - The JVM Instance

 java.lang.System Class - The Operating System

 ClassLoader Class - Class Loaders

Class Class - Class Reflections

 What Is java.lang.Class Class?

forName() Method - Loading Classes

 Class Reflection and Introspection

 Array Class Introspection

 Invoking Methods of Class Instances

 Sun's JVM - Java HotSpot VM

 JRockit JVM 28.2.7 by Oracle Corporation

 JVM Runtime Data Areas

 Memory Management and Garbage Collectors

 Garbage Collection Tests

 JVM Stack, Frame and Stack Overflow

 Thread Testing Program and Result

 CPU Impact of Multi-Thread Applications

 I/O Impact of Multi-Thread Applications

 CDS (Class Data Sharing)

 Micro Benchmark Runner and JVM Options

 Micro Benchmark Tests on "int" Operations

 Micro Benchmark Tests on "long" Operations

 Micro Benchmark Tests in JIT Compilation Mode

 Micro Benchmark Tests on "float" and "double" Operations

 Outdated Tutorials

 References

 PDF Printing Version