Friday, March 2, 2007

Running a class not in the classpath

This piece of code displays the invocation of a class not in the classpath of the application. This can be used to write utilities.

Say I have a jar file present on my system in say a directory "c:/MyUtils" (I have used windows locations, no reason why this should not work on any other OS) named SystemUtils.jar which has a main class in a class com.sash.DoIt. This jar is not in my classpath and I need to execute it. The following piece of code executes the main method.
 File file = new File("c:\\MyUtils\\SystemUtils.jar");
ClassLoader cl = new URLClassLoader(new URL[] { file.toURI().toURL()});
Class cls = cl.loadClass("com.sash.DoIt");
Method mainMethod = cls.getDeclaredMethod("main", new Class[]{String[].class});
mainMethod.invoke(null, new Object[]{null});

Very interesting stuff. Never used it but waiting for the first oppertunity to use this in one of my projects :).

No comments: