Welcome Guest!
Create Account | Login
Locator+ Code:

Search:
FTPOnline
Channels Hot Topics Partner Sites Magazines About FTP RSS 2.0 Feed


email article
printer friendly


Match the Right Constructor
A reader asks about instantiating an object dynamically with a matching constructor

Posted August 25, 2003

Jason, Thank you for your excellent article on ("Plug and Play with Java," by Jason Byassee, Java Pro, July 2003). I am still in the process of studying the article, and I was wondering if I could ask you a question. You mention that a class can be instantiated dynamically by some means using a constructor other than the default. Can you show me what that would look like? For example:

Class c = Class.forName(
  classname);
Object o = c.newInstance();
  // Use default constructor.
ADVERTISEMENT

How do I create one using a constructor that takes parameters? Thanks in advance for any light you can shed.

Brendan Farragher

Jason Byassee Responds: What you need to do is find the constructor that matches the parameter types, and then use that constructor object to call the newInstance() method with the parameter list (as an Object array). This code is a little more complex than using the default constructor (this is pseudocode):

// Create an array of Class 
// objects that match the 
// constructor you are searching 
// for.
// Class[] parameters = 
// new Class[]{…};

// Get the declared constructors 
// for the desired class
Constructor[] cons = 
  c.getDeclaredConstructors();

// Iterate through each 
// constructor and compare the 
// parameter types (Class 
// objects) with the parameter 
// types of the constructor that
// you are searching for.
. . .
Class[] consParams = 
  cons[consIndex].
  getParameterTypes();
. . .
if (consParams[paramIndex].
  isAssignableFrom(
  parameters[paramIndex]))
. . .

// Group (in an Object array) 
// the parameters to be passed 
// to the constructor.

Object parameters[] = 
  new Object[]{…};

// Call the constructor
Object instance = 
  constructor.newInstance(
  parameters);


Back to top














Java Pro | Visual Studio Magazine | Windows Server System Magazine
.NET Magazine | Enterprise Architect | XML & Web Services Magazine
| | Discussions | Newsletters | FTP Home