1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package javax.jdo;
19  
20  import java.io.File;
21  import java.io.IOException;
22  import java.lang.reflect.Method;
23  import java.net.URL;
24  import java.net.URLClassLoader;
25  
26  public class ClasspathHelper {
27  
28      private static URLClassLoader SYSTEM_CLASSLOADER = (URLClassLoader) ClassLoader.getSystemClassLoader();
29      private static Method METHOD;
30      static {
31          try {
32              METHOD = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
33              METHOD.setAccessible(true);
34          }
35          catch (Throwable t) {
36              throw new RuntimeException(t);
37          }
38      }
39  
40      public static void addFile(String s) throws IOException {
41          addFile(s, null);
42      }
43  
44      public static void addFile(File f) throws IOException {
45          addFile(f, null);
46      }
47  
48      public static void addURL(URL u) throws IOException {
49          addURL(u, null);
50      }
51  
52      public static void addFile(String s, URLClassLoader loader) throws IOException {
53          addFile(new File(s), loader);
54      }
55  
56      public static void addFile(File f, URLClassLoader loader) throws IOException {
57          addURL(f.toURL(), loader);
58      }
59  
60      public static void addURL(URL u, URLClassLoader loader) throws IOException {
61          if (loader == null) {
62              loader = SYSTEM_CLASSLOADER;
63          }
64          try {
65              METHOD.invoke(loader, new Object[] { u });
66          }
67          catch (Throwable t) {
68              throw new IOException("Could not add URL to system classloader: " + t.getMessage());
69          }
70      }
71  }
72  
73