You can do this using URLClassLoader, you can get a handle to this through the static getSystemClassLoader() in the ClassLoader class. then add the jar file that you want as a URL and then load that class.
I'd be interested in an example of that because I don't see how to do it.
More commonly, create a new URLClassLoader (or a custom subclass) with the new URL in the constructor arguments. Use that loader to load some anchor for your app, and anything from there down (if you do nothing else to break the chain) will have the same classpath.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Well, i see one big problem with the code above. It assumes that the system class loader is always a URLClassloader! This can be extremely risky considering the fact that anyone can change the system class loader using the property "java.system.class.loader". Moreover, there is no need to get all the urls from the system class loader. As Stan said, just create a new URLCLassloader with the new URL. In case this classloader does not find the specified class in the specified url, it will delegate the class loading to its parent.(By default the parent is the system class loader)
[ November 21, 2007: Message edited by: Nitesh Kant ] [ November 21, 2007: Message edited by: Nitesh Kant ]
By the way, what is the purpose of subclassing URLClassloader ? Can't we use
The addURL() method is protected, not public. So you would need a subclass to access it. However as Stan indicated, it's more common to simply create a newURLClassLoader that has the desired URL in the constructor.
Originally posted by Nitesh Kant: As Stan said, just create a new URLCLassloader with the new URL. In case this classloader does not find the specified class in the specified url, it will delegate the class loading to its parent.(By default the parent is the system class loader)
Actually, it's the other way around. If the parent can't find it, then it tries to find it itself.
From the API:
When requested to find a class or resource, a ClassLoader instance will delegate the search for the class or resource to its parent class loader before attempting to find the class or resource itself.