本文介绍了为什么reflections.getSubTypesOf(Object.class)找不到枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有
Reflections reflections = new Reflections("my.package", classLoader, new SubTypesScanner(false));
然后找到我的枚举类
Set<Class<? extends Enum>> enums = reflections.getSubTypesOf(Enum.class);
但这不是
Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);
这是否有原因?
可重现的示例:
package cupawntae;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
public class Reflector {
public static void main(String[] args) {
Reflections reflections = new Reflections("cupawntae", Reflector.class.getClassLoader(), new SubTypesScanner(false));
System.out.println("Objects: " + reflections.getSubTypesOf(Object.class));
System.out.println("Enums: " + reflections.getSubTypesOf(Enum.class));
System.out.println("Enum's superclass: " + Enum.class.getSuperclass());
}
}
枚举类别:
package cupawntae;
public enum MyEnum {
}
输出:
Objects: [class cupawntae.Reflector]
Enums: [class cupawntae.MyEnum]
Enum's superclass: class java.lang.Object
推荐答案
这实际上是,尽管可以说不是特别清楚或直观:
This is actually documented behaviour, although it's arguably not particularly clear or intuitive:
edit::
在这种情况下, java.lang.Enum
被视为传递类(例如 other.package.OtherClass
),因此不包括在扫描中,这意味着<$ c $的子类c>枚举不包括在内。
In this case java.lang.Enum
counts as a transitive class (like other.package.OtherClass
), and is therefore not included in the scan, meaning subclasses of Enum
are not included.
类似地,如果我们在 Reflections
中进行问题的示例在目标包之外扩展了某些内容,例如
Similarly, if we make Reflections
in the question's example extend something outside the target package, e.g.
public class Reflector extends Exception {
然后在扫描中不再找到该类
then the class is no longer found in the scan
Objects: []
Enums: [class cupawntae.MyEnum]
Enum's superclass: class java.lang.Object
这篇关于为什么reflections.getSubTypesOf(Object.class)找不到枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!