Creating a Class Instance
Home ] Up ] The Class Class ] Examining a Class ] Array Name Encodings ] [ Creating a Class Instance ] The Reflection Classes ]

 

 

You can use the Class class to create a new instance of a specified class, by calling its newInstance() method:

package reflection;

public class NewInstanceTest
{
    public static void main(String[] args)
    {
        try
        {
            Class empClass = Employee.class;
            Employee emp = (Employee) empClass.newInstance();
            emp.init("Eugene McCracken", 34, 45000, 45678);
            System.out.println("Name: " + emp.getName());
            
            Class mgrClass = Class.forName("reflection.Manager");
            Manager mgr = (Manager) mgrClass.newInstance();
            mgr.init("Pietro Botticelli", 385, 50000000, 675978);
            System.out.println("Name: " + mgr.getName());
        }
        catch(ClassNotFoundException e)
        {
            System.err.println("Class not found");
        }
        catch(InstantiationException e)
        {
            System.err.println("Failed to instantiate");
        }
        catch(IllegalAccessException e)
        {
            System.err.println("Unable to access class");
        }
    }
}

which produces the following output:

Name: Eugene McCracken
Name: Pietro Botticelli

The first created instance used a mechanism that depends on the class already having been loaded into the JVM.

The second created instance used the forName() method, which allows you to explicitly load a class (using its fully qualified name) before instantiating it.  The only requirement here is that the class must exist in the class path.

 
The page was last updated February 19, 2008