4

I am trying to use the Reflections API but am finding it hard to get back the classes using a custom annotation.

I pass in a list of URLs from a directory; stepping through the code it appears to find the class that has the annotation.

URLClassLoader urlClassLoader = new URLClassLoader(plugins.toArray(new URL[plugins.size()]), null);

            Reflections reflections = new Reflections(new ConfigurationBuilder()
                    .setUrls(ClasspathHelper.forClassLoader(urlClassLoader))
                    .setScanners(
                            new SubTypesScanner(false),
                            new TypeAnnotationsScanner()));

But the final piece of code where I need the class that contains the annotation always returns and empty set. Am I doing anything obviously wrong?

classes = reflections.getTypesAnnotatedWith(Column.class, true);

Here is the annotation class;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    boolean load() default false;
    Class loaderClass();
    Class criteriaClass();
    String indicator();
    String columnName();
}

It seems the point of failure of me is actually;

return Sets.newHashSet(concat(forNames(annotated, loaders()), forNames(classes, loaders())));

The loaders method returns null. Both the annotated and classes Iterables are filled out.

cbm64
  • 1,059
  • 2
  • 12
  • 24

1 Answers1

2

Ok, so it looks like I was being a bit simplistic...

The subdirectory I was passing in needed to be added to the ClassLoader using the URLClassLoader.

URLClassLoader childURLClassLoader = new URLClassLoader(plugins.toArray(new URL[plugins.size()]), classLoader);

Once I did this and then modified the ConfigurationBuilder;

Reflections reflections = new Reflections(new ConfigurationBuilder()
                    .setScanners(new SubTypesScanner(false), new TypeAnnotationsScanner())
                    .setUrls(ClasspathHelper.forClassLoader(childURLClassLoader)).addClassLoader(childURLClassLoader));

All was well.

cbm64
  • 1,059
  • 2
  • 12
  • 24