Download the JDK
Search the Tutorials
Hide the TOC
Trail: The Reflection API
Lesson: Manipulating Objects
Manipulating Objects
Creating Objects
Using No-Argument Constructors
Using Constructors that Have Arguments
Getting Field Values
Setting Field Values
Invoking Methods
Home Page > The Reflection API > Manipulating Objects
« Previous • Trail • Next »
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:
> - Using No-Argument Constructors
> - Using Constructors that Have Arguments

« Previous • Trail • Next »
Previous page: Manipulating Objects
Next page: Using No-Argument Constructors