我正在使用抽象工厂来返回具体子类的实例。我希望在运行时根据具体类名称的字符串实例化子类。我还需要向构造函数传递参数。类结构如下:
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.<init>()
,随后是堆栈跟踪。
任何帮助都将不胜感激。谢谢!
constructorParam.getClass()
应该返回你所期望的准确参数类型 - Bozho