How to dynamically instantiate a class

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

What I really want to do is something like this:

Main {
string classToInstantiate;
if (something) classToInstantiate = "class1";
if (something) classToInstantiate = "class2";
fn(classToInstantiate);
}

fn (string theClass) {
// logic to instantiate the class that is the value of theClass
}

Any Help will be greatly appreciated.
Alex
 
Alex Munk said:
What I really want to do is something like this:

Main {
string classToInstantiate;
if (something) classToInstantiate = "class1";
if (something) classToInstantiate = "class2";
fn(classToInstantiate);
}

fn (string theClass) {
// logic to instantiate the class that is the value of theClass
}

Any Help will be greatly appreciated.
Alex

For a more elegant architectural solution, read up on the Factory pattern.
Here's a good example:

http://www.devdaily.com/java/java_oo/node106.shtml

Erik
 
What I really want to do is something like this:
Main {
string classToInstantiate;
if (something) classToInstantiate = "class1";
if (something) classToInstantiate = "class2";
fn(classToInstantiate);
}

fn (string theClass) {
// logic to instantiate the class that is the value of theClass
}

You should really use a separate Factory object but for a quick example it
would be

MyAbstractClass a (or IMyInterface a)
if(something) a = new Class1();
if(somethingElse) a = new Class2();

Of course Class1 and Class2 both need to implement IMyInterface or inherit
MyAbstractClass

SP
 
Back
Top