java.lang.Class

One of the members of the java.lang package is a class named Class. Every time the JVM creates an object, it also creates a java.lang.Class object that describes the type of the object. All instances of the same class share the same Class object. You can obtain the Class object by calling the getClass method of the object. This method is inherited from java.lang.Object.

For example, the following code creates a String object, invokes the getClass method on the String instance, and then invokes the getName method on the Class object.

String country = "Fiji";
Class myClass = country.getClass();
System.out.println(myClass.getName()); // prints java.lang.String

As it turns out, the getName method returns the fully qualified name of the class represented by a Class object.

The Class class also brings the possibility of creating an object without using the new keyword. You achieve this by using the two methods of the Class class, forName and newInstance.

public static Class forName(String className)
public Object newInstance()

The static forName method creates a Class object of the given class name. The newInstance method creates a new instance of a class.

The ClassDemo in Listing 5.1 uses forName to create a Class object of the app05.Test class and create an instance of the Test class. Since newInstance returns a java.lang.Object object, you need to downcast it to its original type.

Listing 5.1: The ClassDemo class

package app05;
public class ClassDemo {
    public static void main(String[] args) {
        String country = "Fiji";
        Class myClass = country.getClass();
        System.out.println(myClass.getName());
        Class klass = null;
        try {
            klass = Class.forName("app05.Test");
        } catch (ClassNotFoundException e) {
        }

        if (klass != null) {
            try {
                Test test = (Test) klass.newInstance();
                test.print();
            } catch (IllegalAccessException e) {
            } catch (InstantiationException e) {
            }
        }
    }
}

You might want to ask this question, though. Why would you want to create an instance of a class using forName and newInstance, when using the new keyword is shorter and easier? The answer is because there are circumstances whereby the name of the class is not known when you are writing the program.