mhshams
mhshams

Reputation: 16952

how to pass maven module classes to a maven plugin

I've developed a maven plugin, which can scan classes within a module, to find some specific classes and do something about them.

The problem is that, when I'm using this plugin in a maven module, It's not able to find classes within that module.

I've checked the plugin classpath and it only contains plugin classes and it's dependencies.

Is there any way to automatically include module classes into plugin classpath?

Upvotes: 0

Views: 492

Answers (1)

mhshams
mhshams

Reputation: 16952

I took this approach and apparently it's working:

1 - a MavenProject parameter is needed within your Mojo class:

@Parameter(defaultValue = "${project}", required = true, readonly = true)
private MavenProject project;

2 - and then you can get the classpath elements from project instance:

try {
    Set<URL> urls = new HashSet<>();
    List<String> elements = project.getTestClasspathElements();
                                  //getRuntimeClasspathElements()
                                  //getCompileClasspathElements()
                                  //getSystemClasspathElements()  
    for (String element : elements) {
        urls.add(new File(element).toURI().toURL());
    }

    ClassLoader contextClassLoader = URLClassLoader.newInstance(
            urls.toArray(new URL[0]),
            Thread.currentThread().getContextClassLoader());

    Thread.currentThread().setContextClassLoader(contextClassLoader);

} catch (DependencyResolutionRequiredException e) {
    throw new RuntimeException(e);
} catch (MalformedURLException e) {
    throw new RuntimeException(e);
}

Upvotes: 3

Related Questions