2 * Copyright 2006 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.general;
19 import java.io.IOException;
21 import java.lang.reflect.Method;
24 import java.net.URLClassLoader;
28 * Utility for working with the class loader. Based on the ClassPathHacker
29 * example found on the internet.
31 public class ClassLoaderUtils {
32 // No logging in this class to keep the required class libraries
33 // limited to the standard java classes. This allows use of the
34 // utilities in an environment with a very limited classpath.
35 private static final String JAR_SUFFIX = ".jar";
38 * Adds all jars in the given directory to the class path.
39 * @param aDirectory Directory.
42 public static void addJarsInDirectory(File aDirectory)
44 System.out.println("directory '" + aDirectory + "'");
46 for (File aFile : aDirectory.listFiles()) {
47 System.out.println("Considering '" + aFile.getCanonicalPath() +
50 if (aFile.getName().toLowerCase().endsWith(JAR_SUFFIX)) {
51 System.out.println("Adding '" + aFile.getCanonicalPath() +
59 * Adds a file to the classpath.
60 * @param aFilename Filename to add.
63 public static void addFile(String aFilename) throws IOException {
64 File f = new File(aFilename);
69 * Adds a file to the classpath.
70 * @param aFile File to add.
73 public static void addFile(File aFile) throws IOException {
74 addURL(aFile.toURL());
78 * Adds a url to the classpath.
79 * @param aUrl Url to add.
82 public static void addURL(URL aUrl) throws IOException {
83 URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
84 Class sysclass = URLClassLoader.class;
87 Method method = sysclass.getDeclaredMethod("addURL",
88 new Class[] { URL.class });
89 method.setAccessible(true);
90 method.invoke(sysloader, new Object[] { aUrl });
91 } catch (Throwable t) {
93 throw new IOException(
94 "Error, could not add URL to system classloader");