KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jicengine > expression > ClassLoaderResolver


1 package org.jicengine.expression;
2
3 /**
4  *
5  *
6  *
7  *
8  * @author .timo
9  *
10  */

11
12 public class ClassLoaderResolver {
13
14     private ClassLoaderResolver() {
15     }
16
17     /**
18      * <p>
19      * Resolves the &quot;correct&quot; classloader to use i.e. chooses
20      * between the current classloader or the context classloader.
21      * </p>
22      * <p>
23      * the logic is based on the JavaWorld article 'Find a way out of the ClassLoader
24      * maze' by Vladimir Roubtsov.
25      * </p>
26      *
27      * @param callerClass the class of the object that wants to use the
28      * ClassLoader.
29      */

30     public static ClassLoader JavaDoc getClassLoader(Class JavaDoc callerClass)
31     {
32         ClassLoader JavaDoc callerLoader = callerClass.getClassLoader ();
33         ClassLoader JavaDoc contextLoader = Thread.currentThread().getContextClassLoader();
34
35         ClassLoader JavaDoc result;
36
37         // if 'callerLoader' and 'contextLoader' are in a parent-child
38
// relationship, always choose the child:
39
if( isChild (contextLoader, callerLoader) ){
40             result = callerLoader;
41         }
42         else if (isChild (callerLoader, contextLoader)){
43             result = contextLoader;
44         }
45         else {
46             // just a guess - context should be a better choice, in most cases.
47
result = contextLoader;
48         }
49
50         /*
51         // getSystemClassLoader fails in applets due to security permissions
52         // didn't have time to fix. now JICE can't be deployed as an extension
53
54         ClassLoader systemLoader = ClassLoader.getSystemClassLoader ();
55
56         // precaution for when deployed as a bootstrap or extension class:
57         if( isChild (result, systemLoader)){
58             result = systemLoader;
59         }
60         */

61
62         return result;
63     }
64
65     /**
66      * Returns true if 'loader2' is a delegation child of 'loader1' [or if
67      * 'loader1'=='loader2']. Of course, this works only for classloaders that
68      * set their parent pointers correctly. 'null' is interpreted as the
69      * primordial loader [i.e., everybody's parent].
70      */

71     private static boolean isChild(ClassLoader JavaDoc loader1, ClassLoader JavaDoc loader2)
72     {
73         if (loader1 == loader2){
74             return true;
75         }
76         else if (loader2 == null){
77             return false;
78         }
79         else if (loader1 == null){
80             return true;
81         }
82         else {
83
84             for( ; loader2 != null; loader2 = loader2.getParent() ){
85                 if (loader2 == loader1){
86                     return true;
87                 }
88             }
89
90             return false;
91         }
92     }
93 }
Popular Tags