Re: How do I get an instance of a class given its name?
"Knute Johnson" <nospam@rabbitbrush.frazmtn.com> wrote in message
news:VHUlh.7933$2U4.2983@newsfe16.lga...
Flo 'Irian' Schaetz wrote:
And thus spoke Knute Johnson...
So how then do I pass a parameter to the constructor?
Class[] c = { Integer.class, String.class };
Object[] o = { new Integer(4), "Hello" };
Test t = (Test)Class.
forName("test.Test").
getConstructor(c).
newInstance(o);
For...
public Test(Integer i, String s) {...}
Flo
Thanks Flo, that worked like a charm!
This seems to be a bit silly. In the code above, you say:
Test t = (Test)Class.forName(...).....
Why not just
Test t = new Test(...);
That is, since you declare 't' to be of type Test, you already
must have information about that class from some import.
However, if 't' is known to be of type Mytype or some
possibly unknown subclass of MyType, then it might
make sense to use:
Class c = Class.forName( name );
MyType t = (MyType)c.newInstance();
or
MyType t = (MyType )c.getConstructor(...).newInstance(...);
where MyType is known from some import.
But I would hope that you would check 'c' to ensure it is
indeed a MyType before you try creating an instance of it.
--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project