我正在使用抽象工厂来返回具体子类的实例。我想在运行时实例化子类,给定具体类名的字符串。我还需要将参数传递给构造函数。类结构如下:
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);
}
}
我上面的 attmept 抛出了以下异常:java.lang.NoSuchMethodException: Child.<init>()
,然后是堆栈跟踪。
任何帮助表示赞赏。谢谢!