Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maven plugin can't load class

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.

like image 834
Steve Armstrong Avatar asked May 16 '09 04:05

Steve Armstrong


1 Answers

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");
like image 59
Steve Armstrong Avatar answered Oct 18 '22 14:10

Steve Armstrong