001/** 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved. 004 * 005 * This program and the accompanying materials are dual-licensed under 006 * either the terms of the Eclipse Public License v1.0 as published by 007 * the Eclipse Foundation 008 * 009 * or (per the licensee's choosing) 010 * 011 * under the terms of the GNU Lesser General Public License version 2.1 012 * as published by the Free Software Foundation. 013 */ 014package ch.qos.logback.classic.spi; 015 016import java.net.URL; 017import java.net.URLClassLoader; 018 019/** 020 * An almost trivial no fuss implementation of a class loader following the 021 * child-first delegation model. 022 * 023 * @author Ceki Gulcu 024 */ 025public class LocalFirstClassLoader extends URLClassLoader { 026 027 public LocalFirstClassLoader(URL[] urls) { 028 super(urls); 029 } 030 031 public LocalFirstClassLoader(URL[] urls, ClassLoader parent) { 032 super(urls, parent); 033 } 034 035 public void addURL(URL url) { 036 super.addURL(url); 037 } 038 039 public Class<?> loadClass(String name) throws ClassNotFoundException { 040 return loadClass(name, false); 041 } 042 043 /** 044 * We override the parent-first behavior established by java.lang.Classloader. 045 * 046 * The implementation is surprisingly straightforward. 047 */ 048 protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { 049 050 // First, check if the class has already been loaded 051 Class<?> c = findLoadedClass(name); 052 053 // if not loaded, search the local (child) resources 054 if (c == null) { 055 try { 056 c = findClass(name); 057 } catch (ClassNotFoundException cnfe) { 058 // ignore 059 } 060 } 061 062 // if we could not find it, delegate to parent 063 // Note that we don't attempt to catch any ClassNotFoundException 064 if (c == null) { 065 if (getParent() != null) { 066 c = getParent().loadClass(name); 067 } else { 068 c = getSystemClassLoader().loadClass(name); 069 } 070 } 071 072 if (resolve) { 073 resolveClass(c); 074 } 075 076 return c; 077 } 078}