Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflections from Maven Mojo

I'd like to use Google Reflections to scan classes from the compiled project from my Maven plugin. But plugins by default don't see the compiled classes of the project. From Maven 3 documentation I read:

Plugins that need to load classes from the compile/runtime/test class path of a project need to create a custom URLClassLoader in combination with the mojo annotation @requiresDependencyResolution.

Which is a bit vague to say the least. Basically I would need a reference to a classloader that loads the compiled project classes. How do I get that?

EDIT:

Ok, the @Mojo annotation has requiresDependencyResolution parameter, so that's easy but still need the correct way to build a classloader.

like image 365
vertti Avatar asked Nov 01 '13 07:11

vertti


1 Answers

@Component
private MavenProject project;

@SuppressWarnings("unchecked")
@Override
public void execute() throws MojoExecutionException {
    List<String> classpathElements = null;
    try {
        classpathElements = project.getCompileClasspathElements();
        List<URL> projectClasspathList = new ArrayList<URL>();
        for (String element : classpathElements) {
            try {
                projectClasspathList.add(new File(element).toURI().toURL());
            } catch (MalformedURLException e) {
                throw new MojoExecutionException(element + " is an invalid classpath element", e);
            }
        }

        URLClassLoader loader = new URLClassLoader(projectClasspathList.toArray(new URL[0]));
        // ... and now you can pass the above classloader to Reflections

    } catch (ClassNotFoundException e) {
        throw new MojoExecutionException(e.getMessage());
    } catch (DependencyResolutionRequiredException e) {
        new MojoExecutionException("Dependency resolution failed", e);
    }
}
like image 122
vertti Avatar answered Nov 15 '22 01:11

vertti