jeudi 30 juillet 2015

How to use org.reflections to scan test-classes in Maven plugin (Mojo)

Disclaimer: I know it's possible to do this without the reflections library, but it seems that by using it I could focus on the core functionality of the plugin, not recursively loading and scanning classes for annotations and methods.

I'm in the process of creating a Maven Mojo that needs to access test classes of a maven project with multiple modules. I've successfully POC-ed this and I'm able to retrieve the URL's for all the target/test-classes folders using mavenProject.getTestClasspathElements(), using these URL's I am able to create a "custom" URLClassLoader, and I can manually load any class I name using that class loader.

No errors occur when I use the URL's from that class loader in my ConfigurationBuilder, but it does not find any of my test classes either.

List<ClassLoader> classLoadersList = new LinkedList<>();
classLoadersList.add(getMavenTestClassLoader());
Reflections reflections = new Reflections(new ConfigurationBuilder()
  .setScanners(new SubTypesScanner(false  /*don't exclude Object.class */), new ResourcesScanner())
  .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
  .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("no.company"))));

Set<Class<?>> classes = reflections.getSubTypesOf(Object.class); //Empty set.

The above setup worked fine when run in the context of a jUnit test using the following class loaders:

ClasspathHelper.contextClassLoader();
ClasspathHelper.staticClassLoader();

Does anyone have any ideas on why this doesn't work?





Aucun commentaire:

Enregistrer un commentaire