2 * Copyright 2005-2010 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.classloading;
19 import java.io.IOException;
21 import java.lang.reflect.Method;
24 import java.net.URLClassLoader;
27 * Utility for adding jars to the system class loader.
29 public class ClassLoaderUtils {
30 // No logging in this class to keep the required class libraries
31 // limited to the standard java classes. This allows use of the
32 // utilities in an environment with a very limited classpath.
33 private static final String JAR_SUFFIX = ".jar";
36 * Adds all jars in the given directory to the class path.
42 public static void addJarsInDirectory(File aDirectory) throws IOException {
43 System.out.println("directory '" + aDirectory + "'");
45 for (File aFile : aDirectory.listFiles()) {
47 .println("Considering '" + aFile.getCanonicalPath() + "'");
49 if (aFile.getName().toLowerCase().endsWith(JAR_SUFFIX)) {
50 System.out.println("Adding '" + aFile.getCanonicalPath() +
58 * Adds a file to the classpath.
64 public static void addFile(String aFilename) throws IOException {
65 File f = new File(aFilename);
70 * Adds a file to the classpath.
76 public static void addFile(File aFile) throws IOException {
77 addURL(aFile.toURI().toURL());
81 * Adds a url to the classpath.
87 public static void addURL(URL aUrl) throws IOException {
88 URLClassLoader sysloader = (URLClassLoader) ClassLoader
89 .getSystemClassLoader();
90 Class sysclass = URLClassLoader.class;
93 Method method = sysclass.getDeclaredMethod("addURL",
94 new Class[] { URL.class });
95 method.setAccessible(true);
96 method.invoke(sysloader, new Object[] { aUrl });
97 } catch (Throwable t) {
99 throw new IOException(
100 "Error, could not add URL to system classloader");