这样做的原因是,
ref.getSubtypesOf(Object.class);
只返回 Object 的直接子类。如果要从扫描的包中获取所有类,则应执行以下操作:
Reflections ref = new Reflections(new ConfigurationBuilder().setScanners(new SubTypesScanner(false), new ResourcesScanner(), new TypeElementsScanner())
...
Set<String> typeSet = reflections.getStore().getStoreMap().get("TypeElementsScanner").keySet();
HashSet<Class<? extends Object>> classes = Sets.newHashSet(ReflectionUtils.forNames(typeSet, reflections
.getConfiguration().getClassLoaders()));
This may look a little hackish but it's the only way I found so far.
Here's a little explanation of what this does:
When Reflections is done with the scanning, it puts all the elements in a multi-value map. In the code example that I pasted, the results are put inside a map with the following keys:
SubTypesScanner, ResourcesScanner, TypeElementsScanner
The ResourceScanner excludes all files ending with .class.
The TypeElementsScanner is a map with a key holding the name of a class, and a value of the fields etc. So if you want to get only the class names, you basically get the key set and later on, convert it to a set if classes.
The SubTypesScanner is also a map, with a key of all the super classes (including Object and interfaces) and values - the classes implementing/extending those interfaces/classes.
如果您愿意,您也可以使用 SubTypesScanner,通过迭代键集并获取所有值,但是如果某个类实现了一个接口,您将不得不处理重复的实体(因为每个类都扩展 Object)。
希望有帮助。