Dynamically add JARs from an application’s lib directory

This example assumes you have the JDBC mm.mysql driver residing in an ext subdirectory.

Main.java:

import java.util.*;
import java.net.*;
import java.io.*;
import java.sql.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      ClassLoader cl = loadExt();
      if (cl != null) {
         cl.loadClass("org.gjt.mm.mysql.Driver").newInstance();
         System.out.println("mysql driver successfully loaded!");
         Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/esus", "USER", "PASS");
 
         //. . .
      }
   }
 
   public static URLClassLoader loadExt() {
      try {
         Vector urls = new Vector();
         File file = new File("ext");
         String[] list = file.list();
         for (int i=0; i<list.length; i++) {
            if (list[i].endsWith(".jar")) {
               urls.add(new URL("file:" + file.getName() + "/" + list[i]));
            }
         }
         return new URLClassLoader((URL[]) urls.toArray( new URL[] { } ));
      } catch ( java.net.MalformedURLException me ) { 
         me.printStackTrace();
      }
 
      return null;
   }
}