To create an object with a constructor that has arguments, you invoke the
The source code for the sample program is:
newInstance
method upon a Constructor
object, not a Class
object. This technique involves several steps: - Create a
Class
object for the object you want to create. - Create a
Constructor
object by invokinggetConstructor
upon theClass
object. ThegetConstructor
method has one parameter: an array ofClass
objects that correspond to the constructor's parameters. - Create the object by invoking
newInstance
upon theConstructor
object. ThenewInstance
method has one parameter: anObject
array whose elements are the argument values being passed to the constructor.
Rectangle
with the constructor that accepts two integers as parameters. Invoking newInstance
upon 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);
newInstance
must be objects. Therefore, each of the primitive int
types is wrapped in an Integer
object. The sample program hardcodes the argument passed to the getConstructor
method. 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]
No comments:
Post a Comment