Using the Reflections library, it's easy:
Reflections reflections = new Reflections("my.pkg", new SubTypesScanner(false));
This scans all classes in url / s that contain the package my.pkg.
- false - does not exclude the Object class, which is excluded by default.
- in some scenarios (different containers) you can pass classLoader as well as a parameter.
So, getting all classes effectively gets all subtypes of Object, transitively:
Set<String> allClasses = reflections.getStore().getSubTypesOf(Object.class.getName());
(The usual way of reflections.getSubTypesOf(Object.class) will load all classes in PermGen and will probably throw OutOfMemoryError, you won't want to do this ...)
If you want to get all the direct subtypes of an object (or any other type) without getting its transitive subtypes at a time, use this:
Collection<String> directSubtypes = reflections.getStore().get(SubTypesScanner.class).get(Object.class.getName());
zapp Mar 09 '13 at 16:25 2013-03-09 16:25
source share