The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: The Reflection API
Lesson: Manipulating Objects

Using No-Argument Constructors

If you need to create an object with the no-argument constructor, you can invoke the newInstance method on a Class  (in the API reference documentation)object. The newInstance method throws a NoSuchMethodException if the class does not have a no-argument constructor. For more information on working with Constructor  (in the API reference documentation)objects, see the section Discovering Class Constructors.

The following sample program creates an instance of the Rectangle class using the no-argument constructor by calling the newInstance method:

import java.lang.reflect.*;
import java.awt.*;

class SampleNoArg {

   public static void main(String[] args) {
      Rectangle r = (Rectangle) createObject("java.awt.Rectangle");
      System.out.println(r.toString());
   }

   static Object createObject(String className) {
      Object object = null;
      try {
          Class classDefinition = Class.forName(className);
          object = classDefinition.newInstance();
      } catch (InstantiationException e) {
          System.out.println(e);
      } catch (IllegalAccessException e) {
          System.out.println(e);
      } catch (ClassNotFoundException e) {
          System.out.println(e);
      }
      return object;
   }
}
The output of the preceding program is:
java.awt.Rectangle[x=0,y=0,width=0,height=0]

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.