|
|
Manipulating Objects |
To create an object with a constructor that has arguments, you invoke thenewInstancemethod upon aConstructorobject, not a
Classobject. This technique involves several steps:
- Create a
Classobject for the object you want to create.- Create a
Constructorobject by invokinggetConstructorupon theClassobject. ThegetConstructormethod has one parameter: an array ofClassobjects that correspond to the constructor's parameters.- Create the object by invoking
newInstanceupon theConstructorobject. ThenewInstancemethod has one parameter: anObjectarray whose elements are the argument values being passed to the constructor.The sample program that follows creates a
Rectanglewith the constructor that accepts two integers as parameters. InvokingnewInstanceupon this constructor is analagous to this statement:This constructor's arguments are primitive types, but the argument values passed toRectangle rectangle = new Rectangle(12, 34);newInstancemust be objects. Therefore, each of the primitiveinttypes is wrapped in anIntegerobject.The sample program hardcodes the argument passed to the
getConstructormethod. In a real-life application such as a debugger, you would probably let the user select the constructor. To verify the user's selection, you could use the methods described in Discovering Class Constructors.The source code for the sample program is:
The sample program prints a description of the constructor and the object that it creates:import java.lang.reflect.*; import java.awt.*; class SampleInstance { public static void main(String[] args) { Rectangle rectangle; Class rectangleDefinition; Class[] intArgsClass = new Class[] {int.class, int.class}; Integer height = new Integer(12); Integer width = new Integer(34); Object[] intArgs = new Object[] {height, width}; Constructor intArgsConstructor; try { rectangleDefinition = Class.forName("java.awt.Rectangle"); intArgsConstructor = rectangleDefinition.getConstructor(intArgsClass); rectangle = (Rectangle) createObject(intArgsConstructor, intArgs); } catch (ClassNotFoundException e) { System.out.println(e); } catch (NoSuchMethodException e) { System.out.println(e); } } public static Object createObject(Constructor constructor, Object[] arguments) { System.out.println ("Constructor: " + constructor.toString()); Object object = null; try { object = constructor.newInstance(arguments); System.out.println ("Object: " + object.toString()); return object; } catch (InstantiationException e) { System.out.println(e); } catch (IllegalAccessException e) { System.out.println(e); } catch (IllegalArgumentException e) { System.out.println(e); } catch (InvocationTargetException e) { System.out.println(e); } return object; } }Constructor: public java.awt.Rectangle(int,int) Object: java.awt.Rectangle[x=0,y=0,width=12,height=34]
|
|
Manipulating Objects |