insatiate a class based on a string

F

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?

String s = "class1";

if (s.equals("class1"))
{
myClass c1 = new class1();
}
else if (s.equals("class2"))
{
myClass c2 = new class2();
}
.....

Thanks,

Frank
 
I

Ingo R. Homann

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?

String s = "class1";

if (s.equals("class1"))
{
myClass c1 = new class1();
}
else if (s.equals("class2"))
{
myClass c2 = new class2();
}
....

Thanks,

Frank

Class.forName(s).newInstance();

Hth,
Ingo
 
D

Daniel Dyer

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();
}
....

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.
 
R

Roedy Green

String s = "class1";

if (s.equals("class1"))
{
myClass c1 = new class1();
}
else if (s.equals("class2"))
{
myClass c2 = new class2();
}
....

see http://mindprod.com/jgloss/classforname.html


--
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,201
Latest member
KourtneyBe

Latest Threads

Top