How to create an object of a particular sub-class of an abstract class based on the classNameString generated on runtime? Let say there is an abstract class A
public abstract class A {
abstract protected void method();
A getNewInstance() throws InstantiationException, IllegalAccessException{
return this.getClass().newInstance();
}
}
Let there be N sub-classes viz A1, A2,.., AN. There is a need to write following method which would return a subclass object based on classNameString
A getSubClassObject(String classNameString)
I have following two ugly implementations
First:
A getSubClassObject(String classNameString){
A obj = null;
if(classNameString.equals("A1")){
obj = new A1();
}else if(classNameString.equals("A2")){
obj = new A2();
}
...
}else if(classNameString.equals("AN")){
obj = new AN();
}
return obj;
}
Second:
A getSubClassObject(String classNameString){
A obj = null;
try {
obj = this.subClassObjectsHashMap().get(classNameString).getNewInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return obj;
}
private HashMap<String, A> subClassObjectsHashMap(){
HashMap<String, A> subClassObjectsHashMap = new HashMap<String,A>();
subClassObjectsHashMap.put("A1", new A1());
subClassObjectsHashMap.put("A2", new A2());
....
subClassObjectsHashMap.put("AN", new AN());
return subClassObjectsHashMap;
}
Are there any better ways to solve this problem?
Yes, if all the constructors receive the same parameter (in your example, no paramaters) you can do
Both methods can throw various exceptions, so you need to add some catch blocks.