Question

Given the following snippet:

Set<Class<? extends MyClass>> allClasses = 
  new Reflections("mypackage").getSubTypesOf(MyClass.class);

The library recursively search for all the classes extending MyClass in the given package and subpackages. I need to do this in the given package only, i.e., not in the subpackages. Is there a way to do so?

Was it helpful?

Solution 2

This is brute force, but:

1) Get subclasses of MyClass. Put in a set.

2) Iterate over classes in the set; remove classes which belong to other packages (i.e. those for which _someClass.getPackage().equals(MyClass.class.getPackage()) is false)

OTHER TIPS

You can use the input filter (a Predicate), so that types in sub packages would not be scan:

new Reflections(new ConfigurationBuilder().
    addUrls(ClasspathHelper.forPackage("my.pack")).
    filterInputsBy(new FilterBuilder().
        include("my\\.pack\\..*\\.class").
        exclude("my\\.pack\\..*\\..*\\.class")));

And of course, you can always (post) filter the results, for example:

import static org.reflections.ReflectionUtils.*;

getAll(reflections.getSubTypesOf(A.class), 
    withPattern(".*my\\.pack\\.(?!.*\\..*).*")); //ouch...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top