The easy way is to make sure the dependent JARs are in the classpath before starting the program.
If you want to load from a sub-directory, you need to determine the path of the JAR to give to the URLClassLoader. You can use something like this to get the path to your program:
new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath())
It's a bit of a hack but I don't know of any official way to get the path to a Java program.
If you want to dynamically load a JAR such that you can use it as if you had specified it in the classpath, check out this thread. It's definitely in the realm of unsupported hack, but it's also simple and easy.
Modified version that I use:
import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
/**
* Hack to modify classpath at runtime. Can be used to load JARs as if they were
* loaded from the start.
*
* Warning: May break if URLClassLoader changes
*
* @author Antony Miguel
*/
public class ClasspathHacker {
/**
* Add a file to the classpath.
*
* @param pPath
* path to the file
*/
public static void addFile(String pPath) {
File f = new File(pPath);
addFile(f);
}
/**
* Add a file to the classpath.
*
* @param pFile
* the file to be added
*/
public static void addFile(File pFile) {
try {
addURL(pFile.toURI().toURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
/**
* Add the content pointed to by a URL to the classpath.
*
* @param pURL
* the URL pointing to the content to be added
*/
public static void addURL(URL pURL) {
/*
* Use reflection to call addURL on the system classloader, which we
* expect to be a URLClassLoader
*/
Method method;
try {
method = URLClassLoader.class.getDeclaredMethod("addURL",
new Class[] { URL.class });
method.setAccessible(true);
method.invoke(ClassLoader.getSystemClassLoader(),
new Object[] { pURL });
} catch (Exception e) {
e.printStackTrace();
}
}
}