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 {
public FooClass(String a, Integer b) {
...
}
}Having this, we'd do the following to prepare the call: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");
Constructor ct = c.getConstructor(proto);
FooClass fc = (FooClass)ct.newInstance(params);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.
4 comments:
Thanks! I was just googling and I found this. I didn't know that you could call newInstance() on a constructor.
Hey! Thanks a million! I was starting to get stressed out with this. I could not find any help. I am back cruising on my project thanks to you!
Well done, this helped me immensely, as did the previous post!
This would not work for primitives - instead of Integer.class, user Integer.TYPE and the constructor with primitive parameters will be yours! Yay!
I got that from this page:
http://www.devx.com/tips/Tip/26362
Thanks for your tutorial though! It was amazingly clear and quick, no nonsense!
Post a Comment