Java – Dynamic loading of class and jar file
By admin on Oct 4, 2007 in Java, open source, Programming
I was asked this question recently to load class or jar file dynamically in Java application. There are few things to take note here
Dynamic Class Loading
To load a class dynamically is straightforward. Just make sure the classpath is defined when your program starts up. E.g., if you define /myapp/classes folder as your classpath during start up, and you have created a new class called com.myapp.NewClass aftert this. All you need to do is to copy NewClass into /myapp/classes/com/myapp
Dynamic Jar Loading
To load a jar dynamically is a bit tricky. There are 2 parts here
- You can load the jar using URLClassLoader. But the existing classpath that you defined during application startup is not changed
- To change the existing classpath, you have to do a bit of hacking to use reflection to modify the existing classpath.
Below is the code snippet I used to load a jar file using URLClassLoader
URLClassLoader clazzLoader ;
Class clazz;
try {
ClassLoaderUtil.addFile(filePath);
filePath = “jar:file://” + filePath + “!/”;
URL url = new File(filePath).toURL();
clazzLoader = new URLClassLoader(new URL[]{url});
clazz = clazzLoader.loadClass(name);
return clazz.newInstance();…….
Take note of the jar:file:// pattern. ClassLoaderUtil will add the new jar file to the existing classpath
public static void addURL(URL u) throws IOException {
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;
try {
Method method = sysclass.getDeclaredMethod(“addURL”, parameters);
method.setAccessible(true);
method.invoke(sysLoader, new Object[]{u});
} catch (Throwable t) {
t.printStackTrace();
throw new IOException(“Error, could not add URL to system classloader”);
}
}
This also bring me another question. How to dynamically unload and reload a class or Jar file ? So far I still don’t know how to do this yet.
Ink | Oct 30, 2007 | Reply
use OSGI to these type of operations
Josh | Feb 5, 2008 | Reply
Given the standard class name like(“package1.className”), you could load a class dynamically using java.lang.reflect.Class’s static forName method:
Class c = Class.forName(“yourClass”);
.. but I want to know how to get an appropriate class name from a file path. That first example omits explaining where the “name” variable came from. It is easy when there are no packages to strip out paths and the file extension but how can you get the appropriate class name with its preceding packages?
admin | Feb 5, 2008 | Reply
Attached the additional code for download..
Adam | Feb 22, 2008 | Reply
> How to dynamically unload and
> reload a class or Jar file ?
http://site.red-illusions.dk/2006/11/04/simple-dynamic-loadingunloading-of-code/
xeus | Mar 28, 2008 | Reply
try using JCL… http://jcloader.sourceforge.net
Heff | Apr 7, 2008 | Reply
You don’t need to unload java classes, the classes will be garbage collected once the classloader is no longer referenced by any objects on the heap. Remember that Classes are also Objects.
Kris | May 7, 2008 | Reply
From where can I get the class ClassLoaderUtil ?
and why is it needed ?
sandipan | Jun 12, 2008 | Reply
after loading a class using the above method i am not able to delete the jar file. The url class loader is not releasing the handle of the jar.
How can i delete the jar after class loading?
shahryar ghazi | Jun 14, 2009 | Reply
thanks for sharing .. very helpful
Bob | May 13, 2010 | Reply
That is a useful post!!!
java multithread program in Eclipse | Nov 18, 2010 | Reply
loading jar was good..
Can explain a program to open website.
In a very simple way.
Thank you.
Jeremy Stongfield | Apr 19, 2012 | Reply
Have you read of Google authorship feature? What do you think about it?
fuhjiree | Jun 6, 2012 | Reply
Hey guys,
I couldn’t agree more. I really donhttp://bestelectricshaverhq.org – ‘t get why more people just don’t get it.
Great post, keep it up.
Cheers!
Amatomealfvot | Dec 23, 2012 | Reply
http://kamagra.4ove.com
cipro company registration order cipro ciprofloxacin hcl 500 ciprofloxacin constipation ciprofloxacin liver cipro chlamydia ciprofloxacin alcohol consumption chlamydia treatment ciprofloxacin
buy cheap ciprofloxacin cheap cipro generic cipro drug uses generic cipro side effects order generic cipro generic cipro warnings generic ciprofloxacin order generic cipro online cheapest ciprofloxacin cheap ciprofloxacin online
Java Experience | Jan 7, 2013 | Reply
Some of JDK classes are automatically loaded into JVM memory which can be seen by using the verbose options
beard trimming kit | Sep 23, 2013 | Reply
Thanks , I’ve just been looking for information about this subject for a long time and
yours is the greatest I have found out till now. However, what concerning the bottom line?
Are you sure concerning the source?
Mitchell | Jun 25, 2014 | Reply
Undeniwbly believe that which you stated. Your favorite reason seemmed too bbe onn the net the simpoest thing too bee aware of.
I sayy to you, I cetainly geet irked while people consider worries that they just don’t know about.
Youu managed to hit tthe nail uon the top as weell as defined out tthe whole
thing without having side effect , people can take
a signal. Willl liikely bbe back to get more. Thanks
yishion | Jul 28, 2014 | Reply
This is truly interesting, it reminded me of qr code reader jar file for java development
coquines | Sep 12, 2014 | Reply
Ѵos articles sont sincèrement plaisants
isi ile daralan makaron | Oct 13, 2014 | Reply
I read this article completely about the resemblance of most up-to-date and previous technologies, it’s awesome
article.
Terje Dahl | Mar 10, 2015 | Reply
Thank you!
Your ClassLoaderUtil fixed my problem!