Here you can find the source of addJars(File directory, boolean recursive)
public static boolean addJars(File directory, boolean recursive)
//package com.java2s; /*//from w w w .ja v a 2 s . c o m * Copyright (c) 2009 * * This file is part of HibernateJConsole. * * HibernateJConsole is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HibernateJConsole is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HibernateJConsole. If not, see <http://www.gnu.org/licenses/>. */ import java.io.File; import java.io.FilenameFilter; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; public class Main { private static Method addURL; public static boolean addJars(File directory, boolean recursive) { return addJars(directory, recursive, null); } public static boolean addJars(File directory, boolean recursive, FilenameFilter filter) { File[] files = directory.isFile() ? new File[] { directory } : directory.listFiles(filter); return addJars(files, recursive); } public static boolean addJars(File[] file, boolean recursive) { return addJars(file, recursive, null); } public static boolean addJars(File[] file, boolean recursive, FilenameFilter filter) { if (file == null || file.length == 0) return false; List<URL> jars = new ArrayList<URL>(file.length); for (File f : file) { if (f.isDirectory()) { if (recursive) addJars(f.listFiles(filter), recursive, filter); continue; } if (filter != null && !filter.accept(f.getParentFile(), f.getName())) continue; if (f.getName().toLowerCase().endsWith(".jar")) try { jars.add(f.toURI().toURL()); } catch (MalformedURLException e) { e.printStackTrace(); } } addURLs(jars); return !jars.isEmpty(); } public static void addURLs(List<URL> urls) { URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); try { for (URL url : urls) { addURL.invoke(sysloader, url); // Reconstruct classpath property if ("file".equals(url.getProtocol())) { String cp = System.getProperty("java.class.path", ""); System.setProperty("java.class.path", ("".equals(cp) ? cp : cp + File.pathSeparatorChar) + new File(url.toURI()).getCanonicalPath()); } } } catch (Throwable t) { throw new RuntimeException("Error, could not add URL to system classloader", t); } } }