Sunday, November 20, 2005

Java: Dynamic class loading, part 2

As we saw in a previous post, Java has the ability to dynamically load classes based on their name. We previously assumed that the classes being loaded had a constructor with no arguments. However, this restriction is ficticious. Let's now see how to load a class with random constructors.

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];
proto[0] = String.class;
proto[1] = Integer.class;

Object[] params = new Object[2];
params[0] = "foo";
params[1] = new Integer(5);
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.

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.

3 comments:

Anonymous said...

Thanks! I was just googling and I found this. I didn't know that you could call newInstance() on a constructor.

Anonymous said...

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!

Anonymous said...

Well done, this helped me immensely, as did the previous post!