01: package org.jicengine.expression;
02:
03: /**
04: *
05: *
06: *
07: *
08: * @author .timo
09: *
10: */
11:
12: public class ClassLoaderResolver {
13:
14: private ClassLoaderResolver() {
15: }
16:
17: /**
18: * <p>
19: * Resolves the "correct" 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 getClassLoader(Class callerClass) {
31: ClassLoader callerLoader = callerClass.getClassLoader();
32: ClassLoader contextLoader = Thread.currentThread()
33: .getContextClassLoader();
34:
35: ClassLoader 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: } else if (isChild(callerLoader, contextLoader)) {
42: result = contextLoader;
43: } else {
44: // just a guess - context should be a better choice, in most cases.
45: result = contextLoader;
46: }
47:
48: /*
49: // getSystemClassLoader fails in applets due to security permissions
50: // didn't have time to fix. now JICE can't be deployed as an extension
51:
52: ClassLoader systemLoader = ClassLoader.getSystemClassLoader ();
53:
54: // precaution for when deployed as a bootstrap or extension class:
55: if( isChild (result, systemLoader)){
56: result = systemLoader;
57: }
58: */
59:
60: return result;
61: }
62:
63: /**
64: * Returns true if 'loader2' is a delegation child of 'loader1' [or if
65: * 'loader1'=='loader2']. Of course, this works only for classloaders that
66: * set their parent pointers correctly. 'null' is interpreted as the
67: * primordial loader [i.e., everybody's parent].
68: */
69: private static boolean isChild(ClassLoader loader1,
70: ClassLoader loader2) {
71: if (loader1 == loader2) {
72: return true;
73: } else if (loader2 == null) {
74: return false;
75: } else if (loader1 == null) {
76: return true;
77: } else {
78:
79: for (; loader2 != null; loader2 = loader2.getParent()) {
80: if (loader2 == loader1) {
81: return true;
82: }
83: }
84:
85: return false;
86: }
87: }
88: }
|