> Class c = Class.forName(classname);
> classname c = new classname();
>
> Doesn't seem to compile. My understanding is that the first line creates
> c as a class whose name is classname.
The class loader simply loads the class called classname.
A reference to the class is returned and assigned to 'c'.
> But I can't seem to use line 2 to
> instantiate an object of that class.
Why not ? There is nothing special you are doing (that we can see) that
prevents such a thing.
What is the compile-time error ?
> Do I have to use getConstructor()?
No.
> I can't seem to find any specific examples of this in the Sun tutorials,
> perhaps someone can straighten me out. Thanks in advance.
You are performing a dynamic class load, followed by a static instantiation.
Very odd. Do you mean to instantiate the Class object ?
Use the newInstance() method.
If you haven't got a default constructor (speculating that this is the
source of your compile-time error), then this will cause an exception.
More information required (the compile-time error).

Signature
Tony Morris
(BInfTech, Cert 3 I.T.)
Software Engineer
(2003 VTR1000F)
Sun Certified Programmer for the Java 2 Platform (1.4)
Sun Certified Developer for the Java 2 Platform
fishfry - 02 Mar 2004 08:22 GMT
> > Class c = Class.forName(classname);
> > classname c = new classname();
[quoted text clipped - 22 lines]
> source of your compile-time error), then this will cause an exception.
> More information required (the compile-time error).
Ok I have a dynamic instantiation going like so:
Class c = Class.forName(classname);
Object o = c.newInstance();
That is working ok. However now I need to pass an argument to the
constructor:
Object o = c.newInstance("foo")
The compiler complains "newInstance() in java.lang.Class cannot be
applied to (java.lang.String)"
Collin VanDyck - 02 Mar 2004 16:15 GMT
> Ok I have a dynamic instantiation going like so:
>
[quoted text clipped - 8 lines]
> The compiler complains "newInstance() in java.lang.Class cannot be
> applied to (java.lang.String)"
Try using the Class.getDeclaredConstructor(Class[] parameterTypes) to get
the Constructor.
ex:
Class[] parameterTypes = new Class[1];
parameterTypes[0] = "".getClass();
Constructor constructorWithStringParam =
c.getDeclaredConstructor(parameterTypes);
Once you have the Constructor, use
Constructor.newInstance(Object[] initargs)
ex:
Object[] initargs = new Object[1];
initargs[0] = "first param";
Object o = constructorWithStringParam.newInstance(initargs);
To call the constructor with the String argument.
-CV
> Class c = Class.forName(classname);
> classname c = new classname();
>
> Doesn't seem to compile.
Provide REAL code and the REAL error message.
/Thomas