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 explicitly:

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 = null;
   // d = (java.util.Date) c.newInstance(); // deprecated
   d = (java.util.Date) c.getDeclaredConstructor().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) 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 create a new instance
      try {
         c = Class.forName("java.util.Random");
         o = c.getDeclaredConstructor().newInstance();
         java.util.Random r = (java.util.Random) o;
         out.println("Random number: "+r.nextInt());
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

When executed, I got this result:

herong> java ClassForName
Random number: -1655424893

herong> java ClassForName
Random number: 1511927719

herong> java ClassForName
Random number: 1247702944

Note that:

Table of Contents

 About This Book

 JVM (Java Virtual Machine) Specification

 Java HotSpot VM - JVM by Oracle/Sun

 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

 JVM Runtime Data Areas

 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

 OpenJ9 by Eclipse Foundation

 JRockit JVM 28.2.7 by Oracle Corporation

 Archived Tutorials

 References

 Full Version in PDF/EPUB