3

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?

Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94

2 Answers2

3

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...
zapp
  • 1,533
  • 1
  • 14
  • 18
  • I tried a few combinations using filters but I think I have found [a bug](https://github.com/ronmamo/reflections/issues/26) preventing this from being useful. – Giovanni Botta May 15 '14 at 13:37
1

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)

Anna Dickinson
  • 3,307
  • 24
  • 43
  • I don't think you understood the question. This has nothing to do with subclasses, but subpackages. – Giovanni Botta May 01 '14 at 21:18
  • Oh, sorry -- read that wrong. But, you could still use a brute-force approach: iterate over all the classes returned by getSubTypesOf and remove those for which (_someClass.getPackage().equals(MyClass.class.getPackage()) is false. – Anna Dickinson May 01 '14 at 21:32
  • 1
    Update the answer and I'll accept. I ended up doing something along those line because of what seems to be [a bug in the filter](https://github.com/ronmamo/reflections/issues/26). – Giovanni Botta May 15 '14 at 13:38