Was wondering if there was a better way to insatiate a class based on
some string variable read from a properties file then an if-then-else?
String s = "class1";
if (s.equals("class1"))
{
myClass c1 = new class1();
}
else if (s.equals("class2"))
{
myClass c2 = new class2();
}
....
Thanks,
Frank
Ingo R. Homann - 14 Jul 2005 14:51 GMT
Hi frank,
> Was wondering if there was a better way to insatiate a class based on
> some string variable read from a properties file then an if-then-else?
[quoted text clipped - 14 lines]
>
> Frank
Class.forName(s).newInstance();
Hth,
Ingo
Daniel Dyer - 14 Jul 2005 14:55 GMT
> Was wondering if there was a better way to insatiate a class based on
> some string variable read from a properties file then an if-then-else?
[quoted text clipped - 10 lines]
> }
> ....
Use reflection. Take a look at the methods in the Class class
(http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html),
particularly the forName and newInstance methods. You may also need the
getConstructor method and the java.lang.reflect.Constructor class if your
constructors have parameters.
Dan.

Signature
Daniel Dyer
http://www.dandyer.co.uk
frank - 14 Jul 2005 16:13 GMT
Thanks!!!
>> Was wondering if there was a better way to insatiate a class based on
>> some string variable read from a properties file then an if-then-else?
[quoted text clipped - 18 lines]
>
> Dan.
Roedy Green - 14 Jul 2005 22:25 GMT
>String s = "class1";
>
[quoted text clipped - 7 lines]
>}
>....
see http://mindprod.com/jgloss/classforname.html

Signature
Bush crime family lost/embezzled $3 trillion from Pentagon.
Complicit Bush-friendly media keeps mum. Rumsfeld confesses on video.
http://www.infowars.com/articles/us/mckinney_grills_rumsfeld.htm
Canadian Mind Products, Roedy Green.
See http://mindprod.com/iraq.html photos of Bush's war crimes