我正在使用抽象工廠來返回具體子類的實例。我想在運行時實例化子類,給定具體類名的字符串。我也需要傳遞一個參數給構造函數。類結構如下:在運行時的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