001package org.andromda.maven.plugin.configuration;
002
003import java.net.URL;
004import java.net.URLClassLoader;
005
006/**
007 * A custom class loader necessary to avoid class loading errors
008 * when running within Maven2.
009 *
010 * @author Chad Brandon
011 */
012public class ConfigurationClassLoader
013    extends URLClassLoader
014{
015    /**
016     * @param urls
017     * @param parent
018     */
019    public ConfigurationClassLoader(
020        final URL[] urls,
021        final ClassLoader parent)
022    {
023        super(urls, parent);
024    }
025
026    /**
027     * @see ClassLoader#loadClass(String)
028     */
029    public Class loadClass(final String name)
030        throws ClassNotFoundException
031    {
032        return this.loadClass(
033            name,
034            false);
035    }
036
037    /**
038     * @see ClassLoader#loadClass(String, boolean)
039     */
040    protected synchronized Class loadClass(
041        final String name,
042        final boolean resolve)
043        throws ClassNotFoundException
044    {
045        // - first, we check if the class has already been loaded
046        Class loadedClass = this.findLoadedClass(name);
047
048        // - if we could not find it, try to find it in the parent
049        if (loadedClass == null)
050        {
051            final ClassLoader parent = this.getParent();
052            if (parent != null)
053            {
054                try
055                {
056                    loadedClass = parent.loadClass(name);
057                }
058                catch (final ClassNotFoundException exception)
059                {
060                    // - ignore
061                }
062            }
063            else
064            {
065                loadedClass = getSystemClassLoader().loadClass(name);
066            }
067        }
068
069        // - if not loaded from the parent, search this classloader
070        if (loadedClass == null)
071        {
072            loadedClass = findClass(name);
073        }
074
075        if (resolve)
076        {
077            this.resolveClass(loadedClass);
078        }
079
080        return loadedClass;
081    }
082}