有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带有子类的Java反射

我试图使用反射(由org.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.commandPlayerCommandSimpleCommand或仅仅Command中扩展了三个抽象类中的一个PlayerCommandSimpleCommand也扩展了Command

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

如何使反射代码针对所有扩展Command的类和任何扩展Command的类


共 (1) 个答案

  1. # 1 楼答案

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

    问题是,并不是所有的类都在advanced中被类加载器加载和知道,因此您不会在结果列表中看到它