Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I instantiate a class given its string name?

I have an abstract class and I want to initalize it to a class that extends it.

I have the child classes name as a string.

Besides this...

String childClassString; MyAbstractClass myObject;  if (childClassString = "myExtenedObjectA")     myObject = new ExtenedObjectA(); if (childClassString = "myExtenedObjectB")     myObject = new ExtenedObjectB(); 

How can I do this? Basically how do I get rid of the if statements here?

like image 902
ctrlShiftBryan Avatar asked Feb 11 '10 20:02

ctrlShiftBryan


People also ask

How do you instantiate a class dynamically in Java?

If your class has a no-arg constructor, you can get a Class object using Class. forName() and use the newInstance() method to create an instance (though beware that this method is often considered evil because it can defeat Java's checked exceptions).


2 Answers

Look at Activator.CreateInstance().

myObject = (MyAbstractClass)Activator.CreateInstance("AssemblyName", "TypeName"); 

or

var type = Type.GetType("MyFullyQualifiedTypeName"); var myObject = (MyAbstractClass)Activator.CreateInstance(type); 
like image 153
Seth Petry-Johnson Avatar answered Oct 01 '22 18:10

Seth Petry-Johnson


I believe this should work:

myObject = (MyAbstractClass)Activator.CreateInstance(null, childClassString); 

The null in the first parameter defaults to the current executing assembly. For more reference: MSDN

edit: forgot to cast to MyAbstractClass

like image 32
IAbstract Avatar answered Oct 01 '22 17:10

IAbstract