The simplest way to create an object in the Java programming language is to use thenew
operator: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:Rectangle r = new Rectangle();The preceding statement is invalid because theString className;
// . . . load className from the user interface
Object o = new (className); // WRONG!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:
Wednesday, 22 September 2010
Creating Objects using reflection in java
Labels:
java,
Reflection
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment