How to create instance of subclass with constructor from super class

后端 未结 4 2336
时光取名叫无心
时光取名叫无心 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:21

    • Use clazz.getDeclaredConstructors() to get all constructors of the class;
    • Iterate through them to find the best applicable constructor, e.g. pick the zero-args one if a single-Object-arg constructor is not available;
    • Invoke that constructor using the appropriate parameters.

    There is no way for this to be entirely safe, since you can't know in advance whether any applicable public constructors exist for a given class, e.g. the ctor might be private, or the available constructors might not accept parameters of the type you want (e.g. needs a String, but you only have an Object).

提交回复
热议问题