Is it possible to load a jar file (and the classes it contains) that is not
on the class path. I know the disk file, how can I get it loaded?
Thanks
Jon
Roedy Green - 03 Nov 2005 09:30 GMT
On Thu, 3 Nov 2005 08:07:42 -0000, "John Smith"
<usenet123@ntlworld.com> wrote, quoted or indirectly quoted someone
who said :
>Is it possible to load a jar file (and the classes it contains) that is not
>on the class path. I know the disk file, how can I get it loaded?
see http://mindprod.com/jgloss/classloader.html

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
davidsouther@hotmail.com - 03 Nov 2005 14:23 GMT
In Windows do somehting like:
C:>java -jar C:\path\to\file.jar
or:
C:>path C:\path\to
C:>java -jar file.jar
Of course, you will need to make minor (\ -> : etc.) if you're on a
different OS.
DS
chris_k - 03 Nov 2005 16:00 GMT
Hi,
here is an example:
static void urlcl() throws Exception {
URL[] urls = new URL[] {
new File("C:\\global_libs\\somejar.jar").toURL(),
};
URLClassLoader urlCL = new URLClassLoader(urls);
Class clazz = Class.forName("com.somepackage.CustomStringBuffer",
true, urlCL);
Object instance = clazz.newInstance();
System.out.println("toString : " + instance.toString());
System.out.println("hashCode : " + instance.hashCode());
Method meth = clazz.getMethod("append", new Class[]
{String.class});
meth.invoke(instance, new String[] {"test"});
meth = clazz.getMethod("sendBuffer", new Class[] {Writer.class});
Writer pw = new PrintWriter(System.out);
meth.invoke(instance, new Writer[] {pw});
}
The best strategy however is to cast the returned instance to some
interface. This allows for re-loading of classes as soon as there is a
new JAR version (you can monitor for JAR file change).
Have a look at the Javadoc of java.net.URLClassLoader.
HTH,
chris