KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > axis > utils > ClassUtils


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */

16 package org.apache.axis.utils;
17
18 import java.io.InputStream JavaDoc;
19 import java.io.File JavaDoc;
20 import java.net.MalformedURLException JavaDoc;
21 import java.net.URL JavaDoc;
22 import java.net.URLClassLoader JavaDoc;
23 import java.security.AccessController JavaDoc;
24 import java.security.PrivilegedAction JavaDoc;
25
26 /**
27  * Utility methods for Class Loading.
28  *
29  * @author Davanum Srinvas (dims@yahoo.com)
30  * @author Matthew Pocock (matthew_pocock@yahoo.co.uk)
31  */

32 public final class ClassUtils {
33     /** default class loader */
34     private static ClassLoader JavaDoc defaultClassLoader
35             = ClassUtils.class.getClassLoader();
36
37     /** hash table of class loaders */
38     private static java.util.Hashtable JavaDoc classloaders = new java.util.Hashtable JavaDoc();
39
40     /**
41      * Set the default ClassLoader. If loader is null, the default loader is
42      * not changed.
43      *
44      * @param loader the new default ClassLoader
45      */

46     public static void setDefaultClassLoader(ClassLoader JavaDoc loader) {
47       if (loader != null)
48           defaultClassLoader = loader;
49     }
50
51     public static ClassLoader JavaDoc getDefaultClassLoader() {
52         return defaultClassLoader;
53     }
54
55     /**
56      * Set the ClassLoader associated with the given className. If either the
57      * class name or the loader are null, no action is performed.
58      *
59      * @param className the name of a class
60      * @param loader the ClassLoader for the class
61      */

62     public static void setClassLoader(String JavaDoc className, ClassLoader JavaDoc loader) {
63         if (className != null && loader != null)
64             classloaders.put(className, loader);
65     }
66
67     /**
68      * Obtain the ClassLoader (if any) associated with the given
69      * className.
70      *
71      * @param className the name of a class
72      * @return class loader
73      */

74     public static ClassLoader JavaDoc getClassLoader(String JavaDoc className) {
75         if (className == null) {
76             return null;
77         }
78         return (ClassLoader JavaDoc) classloaders.get(className);
79     }
80
81     /**
82      * Deregister the ClassLoader for a given className.
83      *
84      * @param className the name of a class
85      */

86     public static void removeClassLoader(String JavaDoc className) {
87         classloaders.remove(className);
88     }
89
90
91     /**
92      * Use this method instead of Class.forName
93      *
94      * @param className Class name
95      * @return java class
96      * @throws ClassNotFoundException if the class is not found
97      */

98     public static Class JavaDoc forName(String JavaDoc className)
99             throws ClassNotFoundException JavaDoc {
100         return loadClass(className);
101     }
102
103     /**
104      * Use this method instead of Class.forName (String className, boolean init, ClassLoader loader)
105      *
106      * @param _className Class name
107      * @param init initialize the class
108      * @param _loader class loader
109      * @return java class
110      *
111      * @throws ClassNotFoundException if the class is not found
112      */

113     public static Class JavaDoc forName(
114             String JavaDoc _className, boolean init, ClassLoader JavaDoc _loader)
115             throws ClassNotFoundException JavaDoc {
116         
117         // Create final vars for doPrivileged block
118
final String JavaDoc className = _className;
119         final ClassLoader JavaDoc loader = _loader;
120         try {
121             // Get the class within a doPrivleged block
122
Object JavaDoc ret =
123                 AccessController.doPrivileged(
124                     new PrivilegedAction JavaDoc() {
125                         public Object JavaDoc run() {
126                             try {
127                                 return Class.forName(className, true, loader);
128                             } catch (Throwable JavaDoc e) {
129                                 return e;
130                             }
131                         }
132                     });
133             // If the class was located, return it. Otherwise throw exception
134
if (ret instanceof Class JavaDoc) {
135                 return (Class JavaDoc) ret;
136             } else if (ret instanceof ClassNotFoundException JavaDoc) {
137                 throw (ClassNotFoundException JavaDoc) ret;
138             } else {
139                 throw new ClassNotFoundException JavaDoc(_className);
140             }
141         } catch (ClassNotFoundException JavaDoc cnfe) {
142             return loadClass(className);
143         }
144     }
145
146     /**
147      * Loads the class from the context class loader and then falls back to
148      * getDefaultClassLoader().forName
149      *
150      * @param _className Class name
151      * @return java class
152      * @throws ClassNotFoundException if the class is not found
153      */

154     private static Class JavaDoc loadClass(String JavaDoc _className)
155             throws ClassNotFoundException JavaDoc {
156         // Create final vars for doPrivileged block
157
final String JavaDoc className = _className;
158
159         // Get the class within a doPrivleged block
160
Object JavaDoc ret =
161             AccessController.doPrivileged(
162                     new PrivilegedAction JavaDoc() {
163                         public Object JavaDoc run() {
164                             try {
165                                 // Check if the class is a registered class then
166
// use the classloader for that class.
167
ClassLoader JavaDoc classLoader = getClassLoader(className);
168                                 return Class.forName(className, true, classLoader);
169                             } catch (ClassNotFoundException JavaDoc cnfe) {
170                             }
171                             
172                             try {
173                                 // Try the context class loader
174
ClassLoader JavaDoc classLoader =
175                                     Thread.currentThread().getContextClassLoader();
176                                 return Class.forName(className, true, classLoader);
177                             } catch (ClassNotFoundException JavaDoc cnfe2) {
178                                 try {
179                                     // Try the classloader that loaded this class.
180
ClassLoader JavaDoc classLoader =
181                                         ClassUtils.class.getClassLoader();
182                                     return Class.forName(className, true, classLoader);
183                                 } catch (ClassNotFoundException JavaDoc cnfe3) {
184                                     // Try the default class loader.
185
try {
186                                         return defaultClassLoader.loadClass(
187                                                 className);
188                                     } catch (Throwable JavaDoc e) {
189                                         // Still not found, return exception
190
return e;
191                                     }
192                                 }
193                             }
194                         }
195                     });
196
197         // If the class was located, return it. Otherwise throw exception
198
if (ret instanceof Class JavaDoc) {
199             return (Class JavaDoc) ret;
200         } else if (ret instanceof ClassNotFoundException JavaDoc) {
201             throw (ClassNotFoundException JavaDoc) ret;
202         } else {
203             throw new ClassNotFoundException JavaDoc(_className);
204         }
205     }
206
207     /**
208      * Get an input stream from a named resource.
209      * Tries
210      * <ol>
211      * <li>the classloader that loaded "clazz" first,
212      * <li>the system classloader
213      * <li>the class "clazz" itself
214      * </ol>
215      * @param clazz class to use in the lookups
216      * @param resource resource string to look for
217      * @param checkThreadContextFirst check the thread context first?
218      * @return input stream if found, or null
219      */

220     public static InputStream JavaDoc getResourceAsStream(Class JavaDoc clazz, String JavaDoc resource, boolean checkThreadContextFirst) {
221         InputStream JavaDoc myInputStream = null;
222
223         if (checkThreadContextFirst &&
224                 Thread.currentThread().getContextClassLoader() != null) {
225             // try the context class loader.
226
myInputStream =
227                     Thread.currentThread().getContextClassLoader()
228                     .getResourceAsStream(resource);
229         }
230         if (myInputStream == null) {
231             // if not found in context class loader fall back to default
232
myInputStream = getResourceAsStream(clazz, resource);
233         }
234         return myInputStream;
235     }
236     
237     /**
238      * Get an input stream from a named resource.
239      * Tries
240      * <ol>
241      * <li>the classloader that loaded "clazz" first,
242      * <li>the system classloader
243      * <li>the class "clazz" itself
244      * </ol>
245      * @param clazz class to use in the lookups
246      * @param resource resource string to look for
247      * @return input stream if found, or null
248      */

249     public static InputStream JavaDoc getResourceAsStream(Class JavaDoc clazz, String JavaDoc resource) {
250         InputStream JavaDoc myInputStream = null;
251
252         if(clazz.getClassLoader()!=null) {
253             // Try the class loader that loaded this class.
254
myInputStream = clazz.getClassLoader().getResourceAsStream(resource);
255         } else {
256             // Try the system class loader.
257
myInputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resource);
258         }
259         if (myInputStream == null && Thread.currentThread().getContextClassLoader() != null) {
260             // try the context class loader.
261
myInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
262         }
263         if (myInputStream == null) {
264             // if not found in classpath fall back to default
265
myInputStream = clazz.getResourceAsStream(resource);
266         }
267         return myInputStream;
268     }
269
270     /**
271      * Creates a new ClassLoader from a classpath specification and a parent
272      * class loader.
273      * The classpath string will be split using the system path seperator
274      * character (e.g. : or ;), just as the java system-wide class path is
275      * processed.
276      *
277      * @param classpath the classpath String
278      * @param parent the parent ClassLoader, or null if the default is to be
279      * used
280      * @throws SecurityException if you don't have privilages to create
281      * class loaders
282      * @throws IllegalArgumentException if your classpath string is silly
283      */

284     public static ClassLoader JavaDoc createClassLoader(String JavaDoc classpath,
285                                                 ClassLoader JavaDoc parent)
286             throws SecurityException JavaDoc
287     {
288         String JavaDoc[] names = StringUtils.split(classpath, System.getProperty("path.separator").charAt(0));
289
290         URL JavaDoc[] urls = new URL JavaDoc[names.length];
291         try {
292             for(int i = 0; i < urls.length; i++)
293                 urls[i] = new File JavaDoc(names[i]).toURL();
294         }
295         catch (MalformedURLException JavaDoc e) {
296           // I don't think this is possible, so I'm throwing this as an
297
// un-checked exception
298
throw (IllegalArgumentException JavaDoc) new IllegalArgumentException JavaDoc(
299                   "Unable to parse classpath: " + classpath);
300         }
301
302         return new URLClassLoader JavaDoc(urls, parent);
303     }
304 }
305
Popular Tags