Java Instantiate Class at Runtime with parameters

bibs picture bibs · Nov 23, 2011 · Viewed 15.7k times · Source

I am using an abstract factory to return instances of concrete subclasses.I would like to instantiate the subclasses at runtime given a String of the concrete class name. I also need to pass a parameter to the constructors. The class structure is as follows:

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);
    }
}

My attmept above is throwing the following exception: java.lang.NoSuchMethodException: Child.<init>(), followed by the stack trace.

Any help is appreciated. Thanks!

Answer

Bozho picture Bozho · Nov 23, 2011
Constructor<?> c = Class.forName(childClass).getDeclaredConstructor(constructorParam.getClass());
c.setAccessible(true);
c.newInstance(new Object[] {constructorParam});

The getConstructor method takes Class arguments to distinguish between constructors. But it returns only public constructors, so you'd need getDeclaredConstructor(..). Then you'd need setAccessible(true)