Discovering Class Constructors


Class c = someObject.getClass(); Constructor[] constructors = c.getConstructors(); for (int i = 0; i < constructors.length; i++) {    Class[] paramTypes =       constructors[i].getParameterTypes();    for (int k = 0; k < paramTypes.length; k ++) {       String paramTypeStr = paramTypes[k].getName();       System.out.print(paramTypeStr + " ");    }    System.out.println(); }



You can get information about a class's public constructors by calling the getConstructors() method on a Class object. This method returns an array of Constructor objects. Using the Constructor object, you can then get the constructor's name, modifiers, parameter types, and throwable exceptions. The Constructor object also has a newInstance() method that allows you to create a new instance of the constructor's class.

In this phrase, we get all the constructors for the someObject class. For each constructor found, we then get an array of Class objects representing all the parameters for that particular constructor. Finally, we print out each of the parameter types for each constructor.

Note

Note that the first constructor contained in the array of constructors returned will always be the default no argument constructor, if one exists. If no constructors exist, then the no argument constructor is defined by default.


You can also get an individual public constructor instead of all the constructors of an object if you know the constructor's parameter types. The following example shows how you would get an individual constructor:

Class c = someObject.getClass(); Class[] paramTypes = new Class[] {String.class}; Constructor aCnstrct = c.getConstructor(paramTypes);


In this example, we get a Constructor object representing the constructor that takes a single String parameter.

The getConstructors() and getConstructor() methods return only the public constructors. If you want to get all the constructors of a class including those that are private, you can use the getdeclaredConstructors() or getdeclaredConstructor() methods. These methods behave like their getConstructors() and getConstructor() counterparts except that they return all of the constructors including those that are private.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net