01: /**
02: * $Revision: 3617 $
03: * $Date: 2006-03-23 16:41:04 -0800 (Thu, 23 Mar 2006) $
04: *
05: * Copyright (C) 2004 Jive Software. All rights reserved.
06: *
07: * This software is published under the terms of the GNU Public License (GPL),
08: * a copy of which is included in this distribution.
09: */package org.jivesoftware.util;
10:
11: import java.io.InputStream;
12:
13: /**
14: * A utility class to assist with loading classes or resources by name. Many application servers use
15: * custom classloaders, which will break uses of:
16: * <pre>
17: * Class.forName(className);
18: * </pre>
19: *
20: * This utility attempts to load the class or resource using a number of different mechanisms to
21: * work around this problem.
22: *
23: * @author Matt Tucker
24: */
25: public class ClassUtils {
26:
27: private static ClassUtils instance = new ClassUtils();
28:
29: /**
30: * Loads the class with the specified name.
31: *
32: * @param className the name of the class
33: * @return the resulting <code>Class</code> object
34: * @throws ClassNotFoundException if the class was not found
35: */
36: public static Class forName(String className)
37: throws ClassNotFoundException {
38: return instance.loadClass(className);
39: }
40:
41: /**
42: * Loads the given resource as a stream.
43: *
44: * @param name the name of the resource that exists in the classpath.
45: * @return the resource as an input stream or <tt>null</tt> if the resource was not found.
46: */
47: public static InputStream getResourceAsStream(String name) {
48: return instance.loadResource(name);
49: }
50:
51: /**
52: * Not instantiatable.
53: */
54: private ClassUtils() {
55: }
56:
57: public Class loadClass(String className)
58: throws ClassNotFoundException {
59: Class theClass = null;
60: try {
61: theClass = Class.forName(className);
62: } catch (ClassNotFoundException e1) {
63: try {
64: theClass = Thread.currentThread()
65: .getContextClassLoader().loadClass(className);
66: } catch (ClassNotFoundException e2) {
67: theClass = getClass().getClassLoader().loadClass(
68: className);
69: }
70: }
71: return theClass;
72: }
73:
74: private InputStream loadResource(String name) {
75: InputStream in = getClass().getResourceAsStream(name);
76: if (in == null) {
77: in = Thread.currentThread().getContextClassLoader()
78: .getResourceAsStream(name);
79: if (in == null) {
80: in = getClass().getClassLoader().getResourceAsStream(
81: name);
82: }
83: }
84: return in;
85: }
86: }
|