Thursday, September 23, 2010

Creating Objects using reflection in java

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 run time. 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 run time. The method you invoke to create an object dynamically depends on whether or not the constructor you want to use has arguments:


No comments:

Post a Comment

Chitika