I have string which is from external source. Based on this string I have to generate an object. All object which I have to generated extend the same abstract base class. I have a list with relation "string" <-> "class".
My question is where is best way to do this generation and how?
- I can make separate class with method with if-else. And invoke it in place where I need.
- I can put it to this if-else direct in place where I need
- I can put it to abstract class.
- Add to abstract class
Map<String,Class>
and try to use reflection (but I don't know how) - something else?
abstract class Element {
abstract String getType();
}
class AElement extends Element{
String getType(){return "A";}
}
class BElement extends Element{
String getType(){return "B";}
}
class CElement extends Element{
String getType(){return "C";}
}
class MyObject {
Element element;
MyObject(String text){
//here I conscruct my object form string.
String[] elem = text.split(";");
this.element = someMethod(elem[3]);
}
I know that elem[3] will be texts "A", "B" and "C" and then I should create in method someMethod() respective AElement, BElement or CElement object.