简体   繁体   中英

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?

what about doing something like

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

with appropriate error handling?

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.

查看java.lang.Class中的Java API,forName(String)和newInstance()方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM