View Javadoc
1   package com.github.searls.jasmine.thirdpartylibs;
2   
3   import org.apache.maven.artifact.Artifact;
4   
5   import java.io.File;
6   import java.net.URL;
7   import java.net.URLClassLoader;
8   import java.util.ArrayList;
9   import java.util.HashSet;
10  import java.util.List;
11  import java.util.Set;
12  
13  public class ProjectClassLoaderFactory {
14  
15    private final Set<Artifact> artifacts;
16  
17    public ProjectClassLoaderFactory() {
18      this(new HashSet<Artifact>());
19    }
20  
21    public ProjectClassLoaderFactory(Set<Artifact> artifacts) {
22      this.artifacts = artifacts;
23    }
24  
25    public ClassLoader create() {
26      final List<String> classpathElements = new ArrayList<String>();
27      for (Artifact artifact : artifacts) {
28        classpathElements.add(artifact.getFile().getAbsolutePath());
29      }
30      return createURLClassLoader(classpathElements);
31    }
32  
33    private ClassLoader createURLClassLoader(final List<String> classpathElements) {
34      final List<URL> urls = new ArrayList<URL>();
35      try {
36        for (final String element : classpathElements) {
37          final File elementFile = new File(element);
38          urls.add(elementFile.toURI().toURL());
39        }
40      } catch (final Exception e) {
41        throw new RuntimeException(e);
42      }
43      return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader());
44    }
45  }