Instantiating an Object
Home ] Up ] Reconstructing a Class ] Inspecting a Class Instance ] [ Instantiating an Object ] Creating an Array ] Calling a Method ] An Example ]

 

 

Using the class Class, it is possible to dynamically instantiate a class at run time. The following snippet of code shows how this can be done, given just the fully qualified name of the class:

        Class c;
        // Load the class
        try
        {
            c = Class.forName("reflection.Employee");
        }
        catch(ClassNotFoundException e)
        {
            System.err.println("Class not found");
            return;
        }
        
        // Instantiate the class
        Object emp;
        try
        {
            emp = c.newInstance();
        }
        catch(InstantiationException e)
        {
            System.err.println("Failed to instantiate");
        }
        catch(IllegalAccessException e)
        {
            System.err.println("Unable to access class");
        }

If the class file cannot be found in the class path, then a ClassNotFoundException is thrown.

If the specified object cannot be instantiated because it is an interface or is an abstract class, then an InstantiationException is thrown.

If the specified object cannot be instantiated because the caller does not have access to the object's constructor, then an IllegalAccessException is thrown.

Note that the newInstance() method attempts to execute the zero-argument constructor for the class. 

But what if a class doesn't have such a constructor? Does this mean that it can't be dynamically instantiated?

No, it doesn't.  However, it does mean that you can't dynamically instantiate the class using only the class Class.  Instead, you have to use the Constructor class's newInstance() method:

public native Object newInstance(Object[] initargs) 
     throws InstantiationException, 
            IllegalAccessException, 
            IllegalArgumentException, 
            InvocationTargetException

The initargs array supplies the values for the parameters to be passed to the constructor. The newInstance() method attempts to provide the necessary unwrapping conversions from objects (such as Double, Integer, etc.) to any expected primitive types (double, int, etc.)

If the number of actual and formal parameters differ, or if an unwrapping conversion fails, or if there is some other parameter mismatch, then an IllegalArgumentException is thrown.

If the constructor throws an exception, then the exception is wrapped in an InvocationTargetException, which is then thrown.

Here's a snippet of code to show how you do it:

        Class c;
        // Load the class
        try
        {
            c = Class.forName("reflection.Employee");
        }
        catch(ClassNotFoundException e)
        {
            System.err.println("Class not found");
            return;
        }
        
        // Find a suitable constructor
        Class[] paramTypes = new Class[] 
        {
            String.class, int.class, double.class, long.class
        };
        Constructor con;
        try
        {
            con = c.getConstructor(paramTypes);
        }
        catch(NoSuchMethodException e)
        {
            System.err.println("Can't find constructor");
            return;
        }
        
        // Construct the parameters for the call
        Object[] params = new Object[]
        {
            "Frodus G. Eklogue", new Integer(45),
            new Double(34000), new Long(23456)
        };
        
        // Make the call to instantiate an Employee
        Object emp = null;
        try
        {
            emp = con.newInstance(params);
        }
        catch(InstantiationException e)
        {
            System.err.println("Failed to instantiate");
        }
        catch(IllegalAccessException e)
        {
            System.err.println("Unable to access class");
        }
        catch(InvocationTargetException e)
        {
            System.err.println("Invocation target threw exception");
        }

 

The page was last updated February 19, 2008