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.
@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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With