| Author |
Dynamic Constructor call
|
Balasubramanian Chandrasekaran
Ranch Hand
Joined: Nov 28, 2007
Posts: 215
|
|
Hi folks, Happy to be here after a long time. I have situation to solve with my application. I have just tried a prototype implementation.But, that itself went wrong.Here is my situation I need to call a class constructor dynamically.Consider i have two class A and B. Class A code is Class B code Now i executed Class B to get Class A instance.But, the constructor in Class A didn't executed at all(i.e.,)I am not able to see that println statement in console.What modification i have to do in Class B to dynamically call Class A constructor. Thanks in advance.
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24041
|
|
You didn't construct an instance of A; you only loaded the class. Next you have to call newInstance() on the Class object returned by Class.forName(); that will call the default (no argument) constructor. If you need to call a constructor with arguments, then you have to get a Constructor object from the Class object using getConstructor(), getConstructors(), or getDeclaredConstructors() in Class, then invoke the newInstance() method of the Constructor object, passing the appropriate arguments.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Balasubramanian Chandrasekaran
Ranch Hand
Joined: Nov 28, 2007
Posts: 215
|
|
Originally posted by Ernest Friedman-Hill: You didn't construct an instance of A; you only loaded the class. Next you have to call newInstance() on the Class object returned by Class.forName(); that will call the default (no argument) constructor. If you need to call a constructor with arguments, then you have to get a Constructor object from the Class object using getConstructor(), getConstructors(), or getDeclaredConstructors() in Class, then invoke the newInstance() method of the Constructor object, passing the appropriate arguments.
Actually i have seen Javadoc for Class.forName() which states that it will return a instance of that particular class so i thought it will automatically construct an instance of class A. Thanks i got it working now i will try Constructor with arguments later. [ April 04, 2008: Message edited by: Balasubramanian Chandrasekaran ]
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
Originally posted by Balasubramanian Chandrasekaran: Actually i have seen Javadoc for Class.forName() which states that it will return a instance of that particular class
It wasn't the official Java doc you were reading then. What that actually says is
Returns the Class object associated with the class or interface with the given string name.
|
Joanne
|
 |
 |
I agree. Here's the link: jrebel
|
|
subject: Dynamic Constructor call
|
|
|