1 package net.sf.cantina.util;
2
3 import java.lang.reflect.InvocationTargetException;
4 import java.lang.reflect.Method;
5 import java.net.URL;
6
7 /***
8 * This class is a helper to get resources under classpath
9 * @author Stephane JAIS
10 */
11
12 public abstract class Loader
13 {
14
15 /***
16 This method will search for <code>resource</code> in different
17 places. The rearch order is as follows:
18
19 <ol>
20 <p><li>Search for <code>resource</code> using the thread context
21 class loader under Java2. If that fails, search for
22 <code>resource</code> using the class loader that loaded this
23 class (<code>Loader</code>). Under JDK 1.1, only the the class
24 loader that loaded this class (<code>Loader</code>) is used.
25 <p><li>Try one last time with
26 <code>ClassLoader.getSystemResource(resource)</code>, that is is
27 using the system class loader in JDK 1.2 and virtual machine's
28 built-in class loader in JDK 1.1.
29 </ol>
30 */
31
32 public static URL getResource(String resource)
33 {
34 ClassLoader classLoader = null;
35 URL url = null;
36
37 try
38 {
39 classLoader = getClassLoader();
40 if(classLoader != null)
41 {
42
43 url = classLoader.getResource(resource);
44 if(url != null) {
45 return url;
46 }
47 }
48
49
50
51 classLoader = Loader.class.getClassLoader();
52 if(classLoader != null)
53 {
54
55 url = classLoader.getResource(resource);
56 if(url != null)
57 {
58 return url;
59 }
60 }
61 } catch(Throwable t)
62 {
63
64 }
65
66
67
68
69
70
71 return ClassLoader.getSystemResource(resource);
72 }
73
74 /***
75 * Get the Thread Context Loader which is a JDK 1.2 feature. If we
76 * are running under JDK 1.1 or anything else goes wrong the method
77 * returns <code>null<code>.
78 *
79 */
80 private static ClassLoader getClassLoader()
81 throws IllegalAccessException, InvocationTargetException
82 {
83
84 Method method = null;
85 try
86 {
87 method = Thread.class.getMethod("getContextClassLoader", null);
88 } catch (NoSuchMethodException e)
89 {
90
91 return null;
92 }
93 return (ClassLoader) method.invoke(Thread.currentThread(), null);
94 }
95
96
97 public static Class getClass(String name)
98 throws ClassNotFoundException
99 {
100 return Loader.class.getClassLoader().loadClass(name);
101 }
102 }
103