我正在使用一个抽象工厂来返回具体子类的实例。我想在给定具体类名的字符串的情况下在运行时实例化子类。我还需要将参数传递给构造函数。类结构如下:
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>()
,然后是堆栈跟踪。
感谢任何帮助。谢谢!
最佳答案
Constructor<?> c = Class.forName(childClass).getDeclaredConstructor(constructorParam.getClass());
c.setAccessible(true);
c.newInstance(new Object[] {constructorParam});
getConstructor
方法采用Class
参数来区分构造函数。但它仅返回公共(public)构造函数,因此您需要 getDeclaredConstructor(..)
。然后你需要 setAccessible(true)
关于Java 在运行时使用参数实例化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8249050/