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?
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).
Look at Activator.CreateInstance().
myObject = (MyAbstractClass)Activator.CreateInstance("AssemblyName", "TypeName");
or
var type = Type.GetType("MyFullyQualifiedTypeName"); var myObject = (MyAbstractClass)Activator.CreateInstance(type);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With