Reflections by Maven Mojo

I would like to use Google Reflections to crawl classes from a compiled project from my Maven plugin. But plugins do not see compiled project classes by default. From the Maven 3 Documentation I read:

Plugins that need to load classes from the compilation / execution / test path for the project must create their own URLClassLoader in combination with the mojo @requiresDependencyResolution annotation.

This is a bit vague, to say the least. Basically I need a link to a class loader that loads compiled project classes. How to get it?

EDIT:

Well, the @Mojo annotation has a requiresDependencyResolution parameter, so it's easy, but you still need to properly build the class loader.

+8
java maven classloader google-reflections
source share
1 answer
 @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); } } 
+9
source share

All Articles