View Javadoc

1   /*
2    * Copyright 2006-2008 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.osgi.context.internal.classloader;
18  
19  import java.net.URL;
20  
21  import org.springframework.util.Assert;
22  
23  /**
24   * Chaining class loader implementation that delegates the resource and class
25   * loading to a number of class loaders passed in.
26   * 
27   * @author Costin Leau
28   */
29  public class ChainedClassLoader extends ClassLoader {
30  
31  	private final ClassLoader[] loaders;
32  
33  
34  	public ChainedClassLoader(ClassLoader[] loaders) {
35  		Assert.notEmpty(loaders);
36  		for (int i = 0; i < loaders.length; i++) {
37  			ClassLoader classLoader = loaders[i];
38  			Assert.notNull(classLoader, "null classloaders not allowed");
39  		}
40  		this.loaders = (ClassLoader[]) loaders.clone();
41  	}
42  
43  	public URL getResource(String name) {
44  		URL url = null;
45  		for (int i = 0; i < loaders.length; i++) {
46  			ClassLoader loader = loaders[i];
47  			url = loader.getResource(name);
48  			if (url != null)
49  				return url;
50  		}
51  		return url;
52  	}
53  
54  	public Class loadClass(String name) throws ClassNotFoundException {
55  		Class clazz = null;
56  		for (int i = 0; i < loaders.length; i++) {
57  			ClassLoader loader = loaders[i];
58  			try {
59  				clazz = loader.loadClass(name);
60  				return clazz;
61  			}
62  			catch (ClassNotFoundException e) {
63  				// keep moving through the class loaders
64  			}
65  		}
66  		throw new ClassNotFoundException(name);
67  	}
68  }