Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Method to instantiate a particular sub class of an abstract class

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?

like image 435
porsh Avatar asked Jan 01 '26 11:01

porsh


2 Answers

what about doing something like

return (A)Class.forName(runtimeClassName).newInstance();

with appropriate error handling?

like image 193
digitaljoel Avatar answered Jan 02 '26 23:01

digitaljoel


Yes, if all the constructors receive the same parameter (in your example, no paramaters) you can do

Class clazz = Class.forName("fully.qualified.class.nane");
A a = (A) clazz.newInstace();

Both methods can throw various exceptions, so you need to add some catch blocks.

like image 26
Augusto Avatar answered Jan 03 '26 01:01

Augusto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!