February 09, 2007

Dynamic loading of Java classes

Dynamic loading of Java classes at runtime provides tremendous flexibility to you application.
Especially when you are developing complex applications. In java dynamic loading of class is achieved by calling the forName method on the class java.lang.Class. Majority of you must have come across Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") when you did JDBC programs! But what happens behind is not usually told or our curriculum do not go that deep. In this article I will explain how to dynamically load a class and execute it. Lets take a small example:

public class Sample {

public static void main(String args[]) {
System.out.println("Hello World running...");
}
}

Now compile this and let’s try loading it dynamically. Our main program will load this Sample.class dynamically and execute it. Thus we should have the “Hello World running…” displayed!
Lets look at how to load a class and execute it:

import java.lang.reflect.Method;

public class MyLoader
{
public static void main(String[] args) {

boolean mainFound = false;
int i;

try {

Class cl = Class.forName(args[0]);

Method methods[] = cl.getMethods();


for (i=0; i<methods.length; i++) {

if (methods[i].getName().equals("main"))
break;
}

methods[i].invoke(null,new Object[] { args });

} catch(Exception e) {
System.out.println("The exception occured!:");
}
}
}

The java application we want to run is passed as a parameter to Myloader. The program loads the specified class using the forName() method.
An important thing is to find the main method and execute it. To find the main method, we first get all the methods using the getMethods() method. And finally to execute the method, we use the invoke method.

1 comment :

Anonymous said...

Yep you can do that. But if one is very sure about the behaviour they are gonna invoke, then instead of going for reflection looping through all the methods they can just do,

Class oClass = Class.forName( args );
Sample oSample = (Sample)oClass.newInstance();
oSample.testMethod();

Let java do the rest.