1 /*
2 * Copyright (c) 2009 QOS.ch All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 * SOFTWARE.
21 */
22 package ch.qos.cal10n.plugins;
23
24 import java.net.URL;
25 import java.net.URLClassLoader;
26
27 /**
28 * An almost trivial no fuss implementation of a class loader following the
29 * child-first delegation model.
30 *
31 * @author Ceki Gülcü
32 */
33 public class ThisFirstClassLoader extends URLClassLoader {
34
35 public ThisFirstClassLoader(URL[] urls) {
36 super(urls);
37 }
38
39 public ThisFirstClassLoader(URL[] urls, ClassLoader parent) {
40 super(urls, parent);
41 }
42
43 public void addURL(URL url) {
44 super.addURL(url);
45 }
46
47 @Override
48 public Class<?> loadClass(String name) throws ClassNotFoundException {
49 return loadClass(name, false);
50 }
51
52 /**
53 * We override the parent-first behavior established by java.lang.Classloader.
54 *
55 * The implementation is surprisingly straightforward.
56 */
57 protected Class<?> loadClass(String name, boolean resolve)
58 throws ClassNotFoundException {
59
60 // Treating IMessageKeyVerifier as a special case is the whole point of the
61 // exercise.
62 if (name.equals("ch.qos.cal10n.verifier.IMessageKeyVerifier")) {
63 return super.loadClass(name, resolve);
64 }
65
66 // First, check if the class has already been loaded
67 Class<?> c = findLoadedClass(name);
68
69 // if not loaded, search the local (child) resources
70 if (c == null) {
71 try {
72 c = findClass(name);
73 } catch (ClassNotFoundException cnfe) {
74 // ignore
75 }
76 }
77
78 // if we could not find it, delegate to parent
79 // Note that we don't attempt to catch any ClassNotFoundException
80 if (c == null) {
81 if (getParent() != null) {
82 c = getParent().loadClass(name);
83 } else {
84 c = getSystemClassLoader().loadClass(name);
85 }
86 }
87
88 if (resolve) {
89 resolveClass(c);
90 }
91
92 return c;
93 }
94 }