我正在使用抽象工厂来返回具体子类的实例。我想在运行时实例化子类,给定具体类名的字符串。我也需要传递一个参数给构造函数。类结构如下:在运行时的Java实例化类,带参数
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>()
,其次是堆栈跟踪。
任何帮助表示赞赏。谢谢!
我尝试这样做,我仍然看到了同样的错误。我是否需要更改任何构造函数签名?此刻,签名不会明确期望Object类型的参数,而是更具体的东西。 – bibs
你的'constructorParam.getClass()'应该返回你所期望的确切参数类型 – Bozho
根据你的例子,我不确定constructorParam.getClass()是做什么的。你能更好地解释你的答案吗?谢谢! – trusktr