gpt4 book ai didi

带有子类的 Java 反射

转载 作者:行者123 更新时间:2023-12-04 15:29:56 28 4
gpt4 key购买 nike

我正在尝试使用 Reflections(由 org.reflections 提供)来处理一些繁重的工作,因此我不需要在很长的时间内为每个类手动创建一个实例列表。但是,Reflections 并未按照我预期的方式针对类,这导致了一些问题。

我当前的反射代码:

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();
}
}

本质上,我的程序包含 com.example.command.defaults 中的所有命令,它们被分成许多子包,仅用于视觉分组。每个命令都在它自己的类中,它扩展了我们在 com.example.command 中的三个抽象类之一:PlayerCommandSimpleCommand 或只是命令PlayerCommandSimpleCommand 也扩展了 Command

根据我的理解,reflections.getSubTypesOf(Command.class) 应该允许我定位任何以任何方式扩展 Command 的类,但它似乎没有那样工作。使用我的调试器工具,我注意到系统实际上只读取了一个类(仅扩展 Command)。

如何让我的 Reflections 代码以所有扩展 Command 的类和任何扩展 Command 类的类为目标?

最佳答案

根据 API 文档,getSubTypesOf(Class<T> type)获取给定类型的层次结构中的所有子类型,但它还表示这是“取决于 SubTypesScanner 配置的”。

问题是并非所有类都被类加载器提前加载和识别,因此您不会在结果列表中得到它。

关于带有子类的 Java 反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40534780/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com