Maven plugin can't load class

Steve Armstrong picture Steve Armstrong · May 16, 2009 · Viewed 8.2k times · Source

I'm trying to make a maven plugin that needs to use reflection. I want a project to run the plugin, and give it the full name of a class in the project, and the plugin will load it by reflection to get info from it.

There's something strange with the classloader though, because it can't find the class when I use

Class.forName("package.MyClass");

Looking at the "Guide to Maven Classloading", I can't quite figure out if my plugin's classloader, when being run in a different project, has access to that project's classes.

Answer

Steve Armstrong picture Steve Armstrong · May 19, 2009

I'm sure there's a better way, but here's how I got it to work:

Add the following to the javadoc at the top of your mojo: @requiresDependencyResolution runtime

Add a MavenProject parameter:

/**
 * @parameter expression="${project}"
 * @required
 * @readonly
 */
private MavenProject project;

Then you can get the dependencies at runtime, and make your own classloader:

List runtimeClasspathElements = project.getRuntimeClasspathElements();
URL[] runtimeUrls = new URL[runtimeClasspathElements.size()];
for (int i = 0; i < runtimeClasspathElements.size(); i++) {
  String element = (String) runtimeClasspathElements.get(i);
  runtimeUrls[i] = new File(element).toURI().toURL();
}
URLClassLoader newLoader = new URLClassLoader(runtimeUrls,
  Thread.currentThread().getContextClassLoader());

Then you can load your class using this new classloader:

Class bundle = newLoader.loadClass("package.MyClass");