Reputation: 9816
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?
Upvotes: 3
Views: 3752
Reputation: 3347
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)
Upvotes: 2
Reputation: 1553
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...
Upvotes: 3