package jbehave.mojo;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import jbehave.core.behaviour.Behaviours;

/**
 * Extends URLClassLoader to instantiate Behaviours.
 * 
 * @author Mauro Talevi
 */
public class BehavioursClassLoader extends URLClassLoader {

    public BehavioursClassLoader(List classpathElements)
            throws MalformedURLException {
        super(toClasspathURLs(classpathElements), Behaviours.class
                .getClassLoader());
    }

    public BehavioursClassLoader(List classpathElements, ClassLoader parent)
            throws MalformedURLException {
        super(toClasspathURLs(classpathElements), parent);
    }

    /**
     * Loads and instantiates a Behaviours class
     * 
     * @param behavioursName
     *            the name of the Behaviours
     * @return A Behaviours instance
     * @throws IllegalAccessException
     */
    public Behaviours newBehaviours(String behavioursName)
            throws InstantiationException, IllegalAccessException {
        String behavioursNotFound = "The behaviours " + behavioursName
                + " was not found in " + Arrays.toString(getURLs());
        try {
            return (Behaviours) loadClass(behavioursName).newInstance();
        } catch (ClassCastException e) {
            throw new RuntimeException(behavioursName + " is not a "
                    + Behaviours.class.getName(), e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(behavioursNotFound, e);
        } catch (NoClassDefFoundError e) {
            throw new RuntimeException(behavioursNotFound, e);
        }
    }

    protected static URL[] toClasspathURLs(List classpathElements)
            throws MalformedURLException {
        List urls = new ArrayList();
        if (classpathElements != null) {
            for (Iterator i = classpathElements.iterator(); i.hasNext();) {
                String classpathElement = (String) i.next();
                urls.add(new File(classpathElement).toURL());
            }
        }
        return (URL[]) urls.toArray(new URL[urls.size()]);
    }

}

@@ -919,26 +919,8 @@
 Name
-%0A     *           
  the
@@ -1319,22 +1319,38 @@
         
-return
+Behaviours behavious =
  (Behavi
@@ -1392,24 +1392,118 @@
 Instance();%0A
+            Thread.currentThread().setContextClassLoader(this);%0A            return behavious;%0A
         %7D ca

Set BehavioursClassLoader as thread context classloader.