Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  * Licensed to the Apache Software Foundation (ASF) under one or more
0003  * contributor license agreements.  See the NOTICE file distributed with
0004  * this work for additional information regarding copyright ownership.
0005  * The ASF licenses this file to You under the Apache License, Version 2.0
0006  * (the "License"); you may not use this file except in compliance with
0007  * the License.  You may obtain a copy of the License at
0008  *
0009  *    http://www.apache.org/licenses/LICENSE-2.0
0010  *
0011  * Unless required by applicable law or agreed to in writing, software
0012  * distributed under the License is distributed on an "AS IS" BASIS,
0013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014  * See the License for the specific language governing permissions and
0015  * limitations under the License.
0016  */
0017 
0018 package org.apache.spark.util;
0019 
0020 import java.io.IOException;
0021 import java.net.URL;
0022 import java.util.ArrayList;
0023 import java.util.Collections;
0024 import java.util.Enumeration;
0025 
0026 /**
0027  * A mutable class loader that gives preference to its own URLs over the parent class loader
0028  * when loading classes and resources.
0029  */
0030 public class ChildFirstURLClassLoader extends MutableURLClassLoader {
0031 
0032   static {
0033     ClassLoader.registerAsParallelCapable();
0034   }
0035 
0036   private ParentClassLoader parent;
0037 
0038   public ChildFirstURLClassLoader(URL[] urls, ClassLoader parent) {
0039     super(urls, null);
0040     this.parent = new ParentClassLoader(parent);
0041   }
0042 
0043   @Override
0044   public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
0045     try {
0046       return super.loadClass(name, resolve);
0047     } catch (ClassNotFoundException cnf) {
0048       return parent.loadClass(name, resolve);
0049     }
0050   }
0051 
0052   @Override
0053   public Enumeration<URL> getResources(String name) throws IOException {
0054     ArrayList<URL> urls = Collections.list(super.getResources(name));
0055     urls.addAll(Collections.list(parent.getResources(name)));
0056     return Collections.enumeration(urls);
0057   }
0058 
0059   @Override
0060   public URL getResource(String name) {
0061     URL url = super.getResource(name);
0062     if (url != null) {
0063       return url;
0064     } else {
0065       return parent.getResource(name);
0066     }
0067   }
0068 }