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 *