Я использую абстрактную фабрику, чтобы возвращать экземпляры конкретных подклассов. Я хотел бы создать экземпляры подклассов во время выполнения с учетом String с именем конкретного класса. Мне также нужно передать параметр конструкторам. Структура класса следующая:
abstract class Parent {
private static HashMap<String, Child> instances = new HashMap<String,Child>()
private Object constructorParameter;
public static Child factory(String childName, Object constructorParam){
if(instances.keyExists(childName)){
return instances.get(childName);
}
//Some code here to instantiate the Child using constructorParam,
//then save Child into the HashMap, and then return the Child.
//Currently, I am doing:
Child instance = (Child) Class.forName(childClass).getConstructor().newInstance(new Object[] {constructorParam});
instances.put(childName, instance);
return instance;
}
//Constructor is protected so unrelated classes can't instantiate
protected Parent(Object param){
constructorParameter = param;
}
}//end Parent
class Child extends Parent {
protected Child(Object constructorParameter){
super(constructorParameter);
}
}
Мой атрибут выше генерирует следующее исключение: java.lang.NoSuchMethodException: Child.
, за которым следует трассировка стека.
Любая помощь приветствуется. Спасибо!