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

Creating Objects

The simplest way to create an object in the Java programming language is to use the new operator:
Rectangle r = new Rectangle();
This technique is adequate for nearly all applications, because usually you know the class of the object at compile time. However, if you are writing development tools, you may not know the class of an object until runtime. For example, a GUI builder might allow the user to drag and drop a variety of GUI components onto the page being designed. In this situation, you may be tempted to create the GUI components as follows:
String className; 

// . . . load className from the user interface

Object o = new (className); // WRONG!
The preceding statement is invalid because the new operator does not accept arguments. Fortunately, with the reflection API you can create an object whose class is unknown until runtime. The method you invoke to create an object dynamically depends on whether or not the constructor you want to use has arguments. This section discusses these topics:

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.