具体的なサブクラスのインスタンスを返す抽象ファクトリを使用しています。実行時に具象クラス名のStringを指定してサブクラスをインスタンス化したいと考えています。私はまた、コンストラクタにパラメータを渡す必要があります。次のようにクラスの構造は次のとおりです。java.lang.NoSuchMethodException: Child.<init>()
、スタックトレースが続く:上記パラメータでランタイムに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は、次の例外をスローしています。
何か助けていただければ幸いです。ありがとう!
あなたのテストに追加します。
あなたは、単に次のようにコンストラクタを呼び出すことができます。コンストラクタシグネチャを変更する必要がありますか?現時点では、シグネチャは、Object型のパラメータを明示的に期待するのではなく、より具体的なものを期待しています。 – bibs
あなたの 'constructorParam.getClass()'は、あなたが期待している正確なパラメータ型を返さなければなりません。 – Bozho
あなたの例に基づいて、constructorParam.getClass()が何をしているのか分かりません。あなたの答えをよりよく説明できますか?ありがとう! – trusktr