Loading a jar that is not on the path

J

John Smith

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
 
D

davidsouther

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
 
C

chris_k

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top