Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2005

Tip: Looking for answers? Try searching our database.

How do I pass parameter when using newInstance

Thread view: 
Tony Johansson - 19 Oct 2005 12:37 GMT
Hello!

I use method forName and newInstance in class Class like this
instance = (GameFactory)(Class.forName(name).newInstance() );

Now to my question:
Assume that name is GameFactory then I want to pass a parameter to the
GameFactory constructor
like this instance = (GameFactory)(Class.forName(name).newInstance(field) );
Here I pass parameter field which is an int but when I do so I get compile
error saying

F:\gameLab\GameFactory.java(15): Cannot find method 'newInstance(int)' in
'java.lang.Class'

How you any idea?

Or is it so that if I want to pass parameter I have to explicitly use new
GameFactory(field);

//Tony
Oliver Wong - 19 Oct 2005 16:06 GMT
> Hello!
>
[quoted text clipped - 16 lines]
> Or is it so that if I want to pass parameter I have to explicitly use new
> GameFactory(field);

   In short, you can't do this. From the JavaDocs:

<quote>
Creates a new instance of the class represented by this Class object. The
class is instantiated as if by a new expression with an empty argument list.
</quote>

   - Oliver
Ian Shef - 19 Oct 2005 19:50 GMT
> Hello!
>
[quoted text clipped - 11 lines]
> F:\gameLab\GameFactory.java(15): Cannot find method 'newInstance(int)'
> in 'java.lang.Class'

<snip>

I don't think that you can do this with Class, but you can use the reflection
package java.lang.reflect .  Use Class.getConstructor or
Class.getConstructors to get an appropriate Constructor.  Then use
Constructor.newInstance to create and initialize an instance.

It is going to be more complex than the no-argument constructor that you were
using before.

Good Luck!

Signature

Ian Shef     805/F6      *    These are my personal opinions    
Raytheon Company         *    and not those of my employer.
PO Box 11337             *
Tucson, AZ 85734-1337    *



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.