How to create instance of subclass with constructor from super class

后端 未结 4 2162
时光取名叫无心
时光取名叫无心 2021-02-19 00:51

I\'d like to create a registry for classes which are subclasses of a super class. The classes are stored in a map which acts as registry. A class is picked from the registry dep

4条回答
  •  迷失自我
    2021-02-19 01:32

    You are using this line to get the constructor

    clazz.getDeclaredConstructor( Object.class);
    

    But your Subclass2 does not have a single argument constructor hence the exception is thrown.

    Use clazz.getDeclaredConstructors() method instead and invoke constructor based on parameters count.

                BaseClass instance;
                // get constructor with parameter
                Constructor constructor = clazz.getDeclaredConstructors()[0];
                if (constructor.getParameterCount() == 1) {
                    instance = (BaseClass) constructor.newInstance(key);
                } else {
                    instance = (BaseClass) constructor.newInstance();
                }  
    

提交回复
热议问题