The first thing we have to do is to create a vector of Class objects that describes the constructors' prototype. Each element corresponds to a function parameter. Similarly, we later create a vector of Object instances that represents the parameters' values. For example, let's consider the following class:
public class FooClass {Having this, we'd do the following to prepare the call:
public FooClass(String a, Integer b) {
...
}
}
Class[] proto = new Class[2];Once we have this, we can proceed to create the instance of the desired class. To do this, we start by loading the class as we did in the former post. With the class loaded (as a Class object), we use the getConstructor method using the constructor's prototype (proto variable) as its single argument; this returns a Constructor object that represents the desired method.
proto[0] = String.class;
proto[1] = Integer.class;
Object[] params = new Object[2];
params[0] = "foo";
params[1] = new Integer(5);
At last, we call the newInstance function over the Constructor object to create a new instance of the requested class (FooClass in our example). Shown as real code:
Class c = Class.forName("FooClass");Note that I've used the Integer class rather than the primitive int type; I'm not yet sure if you can dynamically call a function that uses primitive types in its signature. Also note that the class being loaded, as well as its constructor, are declared public; otherwise, the load will fail.
Constructor ct = c.getConstructor(proto);
FooClass fc = (FooClass)ct.newInstance(params);