Dynamically loading the classes and jar file in Java Environment
Sometimes you need to load the class files or jar files from an external folder after you initialize the java run time environment. To dynamically load the classes, in Java is straight forward. To incorporate this dynamic nature in java, create a folder out side the environment and set that folder as a CLASS PATH for the program. Make sure, you have setted that folder as CLASS PATH for that program before it start to run. Then put your compiled classes in-to that folder. Remember you have to place them in the proper package structure.
E.g., Defined C:/ExternalClassPath/classes folder as your classpath, before start up. And we have a new compiled class is called com.subanu.DynamicTest.class
To include this new compiled class into the program, just copy that new class and past that in to C:/ExternalClassPath/classes/com/subanu/. [ DynamicTest.class is the class ]
But for the jar, its bit more tricky to do dynamic loading in a program. You can use the URLClassLoader classloder mechanism to load that jar in dynamically.
But the existing classpath that you defined during application start up is not changed. Thus, you have to do bit more advanced on URLClassLoader classloder mechanism which modify existing class path.
public class URLClassLoaderUtil extends URLClassLoader {
private static final Class[] parameters = new Class[] { URL.class };
private static Log log = LogFactory.getLog(URLClassLoaderUtil.class);
public URLClassLoaderUtil(URL[] urls) {
super(urls);
}
public void addFile(String path) throws Exception {
String urlPath = "jar:file://" + path + "!/";
try {
this.addJarURL(new URL(urlPath));
} catch (Exception e) {
throw e;
}
}
public void addJarURL(URL u) throws Exception {
try {
URLClassLoader sysLoader = (URLClassLoader) ClassLoader
.getSystemClassLoader();
URL urls[] = sysLoader.getURLs();
for (int i = 0; i < urls.length; i++) {
if (StringUtils.equalsIgnoreCase(urls[i].toString(), u.toString())) {
if (log.isDebugEnabled()) {
log.debug("URL " + u + " is already in the CLASSPATH");
}
return;
}
}
Class sysclass = URLClassLoader.class;
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysLoader, new Object[] { u });
} catch (Exception e) {
e.printStackTrace();
throw new Exception( "Error, could not add URL to system classloader"+ e.getMessage());
}
}
Rembember the jar:file:// pattern. URLClassLoaderUtil will add the new jar file to the existing classpath.
To call this class
URL urls[] = {};
URLClassLoaderUtil urlClassLoaderUtil = new URLClassLoaderUtil(urls);
urlClassLoaderUtil.addFile(externalClassPath + jarFilename);
Download the URLClassLoaderUtil class here.
This Articles was posted on 2:52 AMThursday, February 18, 2010
|
Labels:
Experiences,
Java,
Programming
|
0 comments:
Post a Comment