Saturday, January 10, 2009

Maven plugin ClassNotFoundException

Maven plugins use their own class loader which does not include the current projects class loader. To get the plugin to reference the class loader,
  • include the outputDirectory of the current project into a new URLClassLoader which has the present threads context loader as its parent
  • include all references to classes loaded at the current project to include this new classloader
  • do this at the execute() method of the Mojo.

try {

File classesFolder = new File(this.outputDirectory,"classes");

URL[] urls = new URL[]{classesFolder.toURI().toURL()};
URLClassLoader classLoader = new URLClassLoader(urls, (URLClassLoader)Thread
.currentThread().getContextClassLoader());

Thread.currentThread().setContextClassLoader(classLoader);


} catch (MalformedURLException e1) {
System.out.println("[Fatal Error] Unable to create custom classloader for project");
e1.printStackTrace();
System.exit(0);
}

where outputDirectory is
/**
* Location of the file.
* @parameter expression="${project.build.directory}"
* @required
*/
public static File outputDirectory;

and classes within the plugin that that attempts to load classes within the current project should so something like the following

something like this:
theClass = Class.forName(className,true,Thread.currentThread().getContextClassLoader());