View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.spi;
15  
16  import java.net.URL;
17  import java.net.URLClassLoader;
18  
19  /**
20   * An almost trivial no fuss implementation of a class loader following the
21   * child-first delegation model.
22   * 
23   * @author Ceki Gulcu
24   */
25  public class LocalFirstClassLoader extends URLClassLoader {
26  
27      public LocalFirstClassLoader(URL[] urls) {
28          super(urls);
29      }
30  
31      public LocalFirstClassLoader(URL[] urls, ClassLoader parent) {
32          super(urls, parent);
33      }
34  
35      public void addURL(URL url) {
36          super.addURL(url);
37      }
38  
39      public Class<?> loadClass(String name) throws ClassNotFoundException {
40          return loadClass(name, false);
41      }
42  
43      /**
44       * We override the parent-first behavior established by java.lang.Classloader.
45       * 
46       * The implementation is surprisingly straightforward.
47       */
48      protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
49  
50          // First, check if the class has already been loaded
51          Class<?> c = findLoadedClass(name);
52  
53          // if not loaded, search the local (child) resources
54          if (c == null) {
55              try {
56                  c = findClass(name);
57              } catch (ClassNotFoundException cnfe) {
58                  // ignore
59              }
60          }
61  
62          // if we could not find it, delegate to parent
63          // Note that we don't attempt to catch any ClassNotFoundException
64          if (c == null) {
65              if (getParent() != null) {
66                  c = getParent().loadClass(name);
67              } else {
68                  c = getSystemClassLoader().loadClass(name);
69              }
70          }
71  
72          if (resolve) {
73              resolveClass(c);
74          }
75  
76          return c;
77      }
78  }