[英]Java Reflection with Child Classes
I'm attempting to use Reflections (as provided by org.reflections
) to handle some heavy lifting, and so I don't need to manually create an instance for every class in a very long list. 我正在尝试使用Reflections(由org.reflections
提供)来处理一些繁重的工作,因此我不需要为很长的列表中的每个类手动创建一个实例。 However, Reflections isn't targeting the classes in the way I'd expect, which is causing some issue. 但是,思考并没有按照我期望的方式来定位课程,这导致了一些问题。
My current Reflections code: 我目前的思考代码:
Reflections reflections = new Reflections(this.getClass().getPackage().getName() + ".command.defaults");
Set<Class<? extends Command>> commandClasses = reflections.getSubTypesOf(Command.class);
// Iterate through all the detected/found classes
for (Class c : commandClasses) {
// If a class is abstract, ignore it.
if (Modifier.isAbstract(c.getModifiers())) {
continue;
}
// Attempt to create an instance of the class/command whatever.
try {
c.newInstance();
} catch (InstantiationException | IllegalAccessException ex) {
// For once, the right thing to do is just ignore the exception.
// If a command is loaded but we can't create an instance or we
// can't access it, just skip. But, we'll at least log it (for now).
ex.printStackTrace();
}
}
Essentially, my program has all commands present in com.example.command.defaults
, where they're divided up into a number of sub-packages just for visual grouping. 从本质上讲,我的程序包含com.example.command.defaults
所有命令,它们被分成许多子包,仅用于可视分组。 Each command is in its own class, where it extends one of our three abstract classes in com.example.command
: PlayerCommand
, SimpleCommand
, or just Command
. 每个命令都在它自己的类中,它在com.example.command
扩展了我们的三个抽象类之一: PlayerCommand
, SimpleCommand
或者只是Command
。 PlayerCommand
and SimpleCommand
also extend Command
. PlayerCommand
和SimpleCommand
也扩展了Command
。
From my understanding, reflections.getSubTypesOf(Command.class)
should allow me to target any class that extends Command
in any way, but it doesn't seem to be working that way. 根据我的理解, reflections.getSubTypesOf(Command.class)
应该允许我以任何方式定位任何扩展Command
类,但它似乎没有那样工作。 Using my debugger tool, I've noticed that only a single class (which extends just Command
) is actually being read by the system. 使用我的调试工具,我注意到系统实际上只读取了一个类(只扩展了Command
)。
How can I make my Reflections code target all classes that extend Command
and any classes that extend a class that extends Command
? 我怎么能作出这样的延长我的思考目标代码的所有类Command
,并延伸扩展一个类的任何类Command
?
Acording to the API documentation, getSubTypesOf(Class<T> type)
gets all sub types in hierarchy of a given type but it also stats that this is "depends on SubTypesScanner
configured". 根据API文档, getSubTypesOf(Class<T> type)
获取给定类型的层次结构中的所有子类型,但它也统计“这取决于SubTypesScanner
配置”。
The issue is that not all classes are loaded and known by the class loader in advanced and therefor you don't get it in the result list. 问题是并非所有类都是由高级类加载器加载和知道的,因此你不会在结果列表中得到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.